【发布时间】:2016-10-25 15:57:51
【问题描述】:
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <map>
template <typename T>
auto Copy(T c)
{
std::vector<decltype(c.begin()->first)> lc;
//Copying
return lc;
}
int main()
{
std::map<int, int> map;
Copy(map);
return 0;
}
在上面的代码中,我尝试从map 的键的数据类型中声明一个vector,但出现以下错误 -
"The C++ Standard forbids containers of const elements allocator<const T> is ill-formed."
【问题讨论】:
-
你认为
decltype(c.begin()->first)的类型是什么,为什么? -
如果您知道
T将始终有一个key_type成员,例如std::map或std::unordered_map,那么使用typename T::key_type而不是decltype(...)可能更简单。跨度>
标签: c++ c++11 c++14 type-inference decltype