【问题标题】:How to get the type of elements in a container?如何获取容器中元素的类型?
【发布时间】:2013-05-12 03:26:06
【问题描述】:

假设我有一个这样的向量:

std::vector<int> vec;

那我想知道vec的元素的类型。我怎么才能得到它?太糟糕了decltype(vec[0]) 导致int&amp;

【问题讨论】:

标签: c++


【解决方案1】:

这就是你要找的吗?

std::vector<int>::value_type

你也可以使用

std::remove_reference<decltype(vec[0])>::type

摆脱引用。

另一种选择是使用decltype(vec)::value_type。但是,由于编译器错误,这在 Visual Studio 上不是 currently work。该编译器的解决方法是创建一个中间 typedef

typedef decltype(vec) vec_type;
vec_type::value_type foo;

【讨论】:

  • 如果有decltype(vec)::value_type之类的就更好了。
  • @Mike 确实有效。你用的是 MSVC 不是吗?如果您在任何 decltype 表达式后写入 ::,编译器中存在一个错误会导致错误。
  • MSVC 的另一个解决方法是使用 std::identity::type::value_type
  • @GalDude33 std::identity 是非标准的。它出现在一些标准化前的 C++0x 草案中,但在此过程中被丢弃了。
  • std::identity 确实存在于 VS 中(在 VS2010 上检查) - 一个错误拒绝您简单地编写 decltype(vec)::value_type
【解决方案2】:

对于任何容器类型的对象c,包括arrays 和所有标准库containers,例如std::vectorstd::list

typename std::remove_reference&lt;decltype(*std::begin(c))&gt;::type

【讨论】:

    猜你喜欢
    • 2012-09-05
    • 2019-11-30
    • 1970-01-01
    • 2014-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多