带有迭代器取消引用的decltype的编译错误 [英] Compile error with decltype of iterator de-reference
问题描述
我在这里想念什么?为什么不能使用decltype定义迭代器的value_type?当我使用decltype而不是iterator_traits时,下面的代码会出现难以理解的编译时错误,但前提是我也使用value_type声明向量。
What am I missing here? Why can't I use decltype to define the value_type of an iterator? The code below gets inscrutable compile-time errors when I use decltype rather than iterator_traits, but only if I also use value_type to declare a vector.
Visual Studio 2017,C + +17转15.6预览
Visual Studio 2017, C++17 rev. 15.6 Preview
#include <vector>
template<class Ptr >
void foo(Ptr beg) {
*beg = 1; // Cool, babies.
// using value_type = decltype(*beg); // COMPILER ERROR when buf declared below
using value_type = typename std::iterator_traits<Ptr>::value_type;
std::vector<value_type> buf(1); // Remove this and decltype compiles.
}
int main() {
std::vector<int> bar(1);
foo(std::begin(bar));
*(std::begin(bar)) = 1;
return 0;
}
根据要求...
error C2528: 'const_pointer': pointer to reference is illegal
推荐答案
出于以下原因,您也是出于同样的原因:
It's for the same reason when you have:
void foo(int *beg)
然后
decltype(*beg)
不给您 int
。您在这里获得 int&
。基本上,这就是您的 using
声明最终得到的:一个引用,一个不请自来的搭便车者。
Does not give you an int
. You get an int &
here. That's what, essentially, your using
declaration ends up getting: a reference, an uninvited hitch-hiker.
如果您坚持使用 decltype
,就可以做到:
If you insist on using decltype
, you can do:
using value_type = typename std::remove_reference<decltype(*beg)>::type;
为了抛弃不受欢迎的搭便车者。
In order to ditch the unwelcome hitch-hiker.
这篇关于带有迭代器取消引用的decltype的编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!