【问题标题】:declare a vector through decltype通过 decltype 声明一个向量
【发布时间】: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()-&gt;first)的类型是什么,为什么?
  • 如果您知道T 将始终有一个key_type 成员,例如std::mapstd::unordered_map,那么使用typename T::key_type 而不是decltype(...) 可能更简单。跨度>

标签: c++ c++11 c++14 type-inference decltype


【解决方案1】:

问题在于decltype(c.begin()-&gt;first) 返回一个const int (当使用libstdc++ - 您的示例使用libc++编译)。 p>

正如你的错误告诉你的那样......

C++ 标准禁止 const 元素的容器,因为分配器 格式不正确。

一个可能的解决方案是使用std::decay_t:

std::vector<std::decay_t<decltype(c.begin()->first)>> lc;

这将保证您的示例适用于 libstdc++libc++。或者,std::remove_const_t 也适用于这种特殊情况。

这是working example on wandbox.

【讨论】:

  • 密钥不是必须是const吗?我想知道为什么libc++没有问题。
  • 在某些时候应该只使用key_type typedef 而不是这种复杂的混乱。 @user2079303 总是const int。只是 libc++ 恰好以这样一种方式实现,vector&lt;const int&gt; 不会那么容易爆炸。
  • decay_t 而不是remove_const_t,因为您的目标是获得适合存储的类型,而decay_t 正是这样做的?
猜你喜欢
  • 2013-03-11
  • 2023-04-11
  • 1970-01-01
  • 1970-01-01
  • 2013-10-17
  • 2016-05-23
  • 1970-01-01
  • 1970-01-01
  • 2017-04-05
相关资源
最近更新 更多