C++11 编译器错误,后跟 decltype(var) 后跟内部类型的"var"

C++11 compiler error when using decltype(var) followed by internal type of "var"

本文关键字:var 内部 类型 编译器 后跟 decltype C++11 错误      更新时间:2023-10-16

我使用的是Visual c++ 2010,下面是我的代码片段:

std::set<int> s;
decltype(s)::value_type param = 0;

我得到了以下错误信息,有人可以帮助我吗?

> error C2039: 'value_type' : is not a member of '`global namespace''
> error C2146: syntax error : missing ';' before identifier 'param'

这是去年在Visual Studio Connect上提出的一个错误。问题757545("不能在作用域操作符之前使用decltype ")。

这个问题旁边列出了一个与@iammillind相同的解决方案,除了它使用了在c++ 11发布前不久从<functional>中删除的std::identity,无论出于什么原因。(std::common_type与一个模板参数等效;std::remove_reference在某些情况下是相同的)

我看到在g++ 4.7.2版本中,代码编译得很好。所以它可能是MSVS中的编译器错误。暂时你可以试试下面的方法:

#ifdef COMPILER_BUG_STILL_THERE
template<typename T> struct Get { typedef T type; };
#define DECLTYPE(VAR) Get<decltype(VAR)>::type
#else
#define DECLTYPE(VAR) decltype(VAR)
#endif

用作:

DECLTYPE(s)::value_type param = 0;

免责声明:当然,使用此技巧时,您可能必须在模板内使用typename。为此,您可以再添加一个宏,例如#define TDECLTYPE(VAR) typename DECLTYPE(VAR)