C++ decltype的行为

C++ decltype的行为,c++,visual-studio-2010,c++11,visual-c++,decltype,C++,Visual Studio 2010,C++11,Visual C++,Decltype,假设我有一个stl容器类obj的对象。我可以这样定义相同类型的其他对象: decltype(obj) obj2; decltype(obj)::iterator it = obj.begin(); 但我不能这样为容器声明迭代器: decltype(obj) obj2; decltype(obj)::iterator it = obj.begin(); 为什么??我做错什么了吗?这是因为语言的解析方式 decltype(obj)::iterator it = obj.begin(); 你

假设我有一个stl容器类obj的对象。我可以这样定义相同类型的其他对象:

decltype(obj) obj2;
decltype(obj)::iterator it = obj.begin();
但我不能这样为容器声明迭代器:

decltype(obj) obj2;
decltype(obj)::iterator it = obj.begin();

为什么??我做错什么了吗?

这是因为语言的解析方式

decltype(obj)::iterator it = obj.begin();
你想让它变成

(decltype(obj)::iterator) it;
但事实上,它变成了

decltype(obj) (::iterator) it;
我必须承认,我也很惊讶地看到这种情况,因为我肯定我以前做过。然而,在这种情况下,您可以只使用auto,甚至decltypeobj.begin,但除此之外,您还可以这样做


根据最终的C++0x FDI草案,您的代码格式良好。这是Visual Studio编译器尚未实现的后期更改

同时,解决方法是使用typedef:

typedef decltype(obj) obj_type;
obj_type::iterator it = obj.begin();
编辑:相关章节和诗句为5.1.1/8:

qualified-id: [...] nested-name-specifier templateopt unqualified-id nested-name-specifier: [...] decltype-specifier :: decltype-specifier: decltype ( expression ) 为了完整起见:


在修复VC++的解析器以反映FDI之前,另一个解决方法是使用元函数:

std::identity<decltype(obj)>::type::iterator it = obj.begin();

谢谢你的汽车。但在我看来,类型定义不是个好主意。我这样做是为了避免类型定义。@Mihran Hovsepyan:为什么?你的代码依赖于一个标准的typedef——它很难不依赖typedef。TyPulf在C++中是不可回避的,因为我的类定义是在头中,但是在CPP中是方法,所以每次CPP实现时,我应该打开头,看看成员的类型。但作为每一个程序员,我都想成为lazy@Mihran当前位置我认为你做得太过分了。。。我认为类中只有几个容器,可以为它们提供合理的名称。使用这些typedef将使代码比使用预期的decltypeobj::迭代器更具可读性,而且DeadMG建议的无论如何都可以是本地typedef:void X::foo{typedef decltypemember container_t;container_t::begin it…,这不需要您来回返回标题…然后我也不会这样做…FWIW,std::identity已被删除,因此这实际上依赖于VC2010。尽管编写它很简单。@GMan:对,我提到它只是因为OP的问题是VC++2010特有的。:-]谢谢@JohannesD。如果您编辑您的答案,并添加最终草案的段落号,我将接受您的答案。