首先:如果我的命名有误,我深表歉意!
基本上,我有一个不太常见的愿望来声明一个基于堆栈的容器,例如:
std::map<CString, size_t> ecounts;
然后我想在函数体中再往下迭代 ecounts 的内容,但我真的不想对一堆东西进行 typedef,也不想为了让编译器重新输入上述类型使用我所拥有的...
std::foreach(ecounts.begin(), ecounts.end(), [&] (>>>here is the problem<<< e)
{
... whatever I want to do with e ...
}
当然,我可以使用 typedef,或者我对手动声明 ecounts 的了解:
std::foreach(ecounts.begin(), ecounts.end(), [&] (std::pair<CString,size_t> e)
...
但是,糟糕!我宁愿只声明什么是 ecounts,然后以某种方式使用它的 value_type。但这似乎不起作用:
std::foreach(ecounts.begin(), ecounts.end(), [&] (decltype(ecounts)::value_type e)
...
这只是我的编译器 (vs2010) 的限制,还是 C++ 的限制?
我该如何为此类代码制定一种单一定义规则,最好不必使用 typedef 来实现它(即,我可以执行以下操作):
typedef std::map<CString, size_t> maptype;
typedef maptype::value_type valuetype;
maptype ecounts;
...
std::foreach(ecounts.begin(), ecounts.end(), [&] (valuetype e)
...
这显然不是世界末日,但如果我可以使用 decltype,我会更高兴地减少思考和回溯以实现上述目标......
最佳答案
VS2010 的局限性,因为你想要的添加进入标准太晚了。它应该使用符合标准的编译器进行编译。作为变通方法,只需使用 decltype(*ecounts.begin()) e
。或身份模板:
template<class T>
struct identity{ typedef T type; };
// usage: identity<decltype(ecounts)>::type::value_type
关于c++ - 如何使用 decltype 访问依赖类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8175453/