c++ - 如何使用 decltype 访问依赖类型?

标签 c++ visual-studio-2010 c++11

首先:如果我的命名有误,我深表歉意!

基本上,我有一个不太常见的愿望来声明一个基于堆栈的容器,例如:

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/

相关文章:

c++ - 企业在 Linux 上使用哪些 C/C++ 编译器?

c++ - 嵌入式 mongo - 从内存加载程序集

c++ - 来自 Qt 文件的编译时错误 : expected unqualified-id before ')' token

c++ - std::function 与使用 auto 一样高效吗?

c++:自旋锁或互斥比较(简单计算)

c++ - GCC/G++ 编译器设置 GUI

c++ - Qt项目中如何使用预编译头文件

.net - 为什么关闭 TrackFileAccess 后 Tracker.exe 响应文件仍然出现错误?

c# - WCF 服务库项目找不到对其他项目的引用

c++ - 将 C++11 线程操作与 QThread 操作混合