【问题标题】:How to find out template parameter Type that STL container holds如何找出STL容器持有的模板参数类型
【发布时间】:2013-11-13 02:16:08
【问题描述】:

例如vector<int> coll,持有int 类型的对象。如果我不知道 coll 是持有 int 怎么办(但我知道它是向量),我将如何查找类型信息?

【问题讨论】:

标签: c++ c++11 stl


【解决方案1】:

您可以从对象的value_type获取信息:

using value_type = decltype(coll)::value_type;

static_assert(std::is_same<value_type, int>::value, "Type is not an int");

在 C++11+ 中可以使用 using 别名和 static_assert

虽然这总是可以通过使用模板来确定(这更常见):

template <class T>
void f(std::vector<T>& v); // use T as the type

【讨论】:

  • 值得注意的是,第一种方法仅适用于 C++11,而第二种方法也适用于 C++98/03(没有decltype 关键字)。跨度>
  • @MatteoItalia 是的,decltype 是新的 C++11 功能
  • @MatteoItalia 是的。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-11
  • 1970-01-01
  • 2013-09-07
  • 1970-01-01
  • 2011-06-22
  • 2021-12-04
相关资源
最近更新 更多