#include <iostream> #include <string> #include <vector> #include <type_traits> int main() { std::vector<int> v{1,2,3,4,5}; auto iter = begin(std::move(v)); if(std::is_const<typename std::remove_reference<decltype(*iter)>::type>::value) std::cout<<"is const\n"; return 0; }
http://coliru.stacked-crooked.com/a/253c6373befe8e50
我遇到了这种行为,因为在带有std :: begin的decltype表达式中有一个declval< Container>(). gcc和clang都返回迭代器,在解除引用时会产生const引用.它可能是有意义的,因为r值引用通常绑定到您不想变异的过期对象.但是,我找不到任何关于此的文件来确定它是否符合标准.我找不到Container :: begin()的begin()或ref-qualified重载的任何相关重载.
更新:答案澄清了正在发生的事情,但相互作用可能很微妙,如下所示:
#include <iostream> #include <string> #include <vector> #include <type_traits> int main() { if(std::is_const<typename std::remove_reference<decltype(*begin(std::declval<std::vector<std::string>>()))>::type>::value) std::cout<<"(a) is const\n"; if(!std::is_const<typename std::remove_reference<decltype(*std::declval<std::vector<std::string>>().begin())>::type>::value) std::cout<<"(b) is not const\n"; if(!std::is_const<typename std::remove_reference<decltype(*begin(std::declval<std::vector<std::string>&>()))>::type>::value) std::cout<<"(c) is not const\n"; return 0; }
http://coliru.stacked-crooked.com/a/15c17b288f8d69bd
天真地,你不会期望(a)和(b)的不同结果当:: begin刚刚用调用vector :: begin来定义时.但是缺少std :: begin重载,它采用非const r值引用并返回迭代器(或者返回const_iterator的ref-qualified vector :: begin overload)会导致这种情况发生.
解决方法
>你正在调用std :: begin(std :: vector< int>&&),但是std :: begin has no overload that takes an rvalue:
template< class C > auto begin( C& c ) -> decltype(c.begin()); template< class C > auto begin( const C& c ) -> decltype(c.begin());
>由于reference collapsing,临时(xvalue)将仅绑定到const lvalue引用:
If you call Fwd with an xvalue,we again get Type&& as the type of v. This will not allow you to call a function that takes a non-const lvalue,as an xvalue cannot bind to a non-const lvalue reference. It can bind to a const lvalue reference,so if Call used a const&,we could call Fwd with an xvalue.
(来自链接的答案).
>因此,
template<class C> auto begin(const C& c) -> decltype(c.begin());
正在调用overload,它返回一个const迭代器.
为什么?
因为std :: begin(v)调用v.begin(),which returns a const_iterator
when called on const
instances of std::vector
.