gau*_*waj 1 c++ type-inference decltype c++11 c++14
#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;
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码我尝试vector从键的数据类型声明一个map但是我得到以下错误 -
"The C++ Standard forbids containers of const elements allocator<const T> is ill-formed."
Run Code Online (Sandbox Code Playgroud)
问题是decltype(c.begin()->first)返回a const int (当使用libstdc ++时 - 你的例子用libc ++编译).
因为你的错误告诉你......
C++标准禁止使用const元素的容器,因为allocator <const T>是不正确的.
可能的解决方案是使用std::decay_t:
std::vector<std::decay_t<decltype(c.begin()->first)>> lc;
Run Code Online (Sandbox Code Playgroud)
这将保证您的示例适用于libstdc ++和libc ++.或者,std::remove_const_t也适用于这种特殊情况.
| 归档时间: |
|
| 查看次数: |
887 次 |
| 最近记录: |