通过decltype声明一个向量

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)

Vit*_*meo 5

问题是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也适用于这种特殊情况.

这是关于wandbox的一个工作示例.

  • 是不是要成为`const`的关键?我想知道为什么`libc ++`没有问题. (2认同)