【发布时间】:2013-11-13 02:16:08
【问题描述】:
例如vector<int> coll,持有int 类型的对象。如果我不知道 coll 是持有 int 怎么办(但我知道它是向量),我将如何查找类型信息?
【问题讨论】:
-
为什么你需要确切地知道?你想解决什么问题?
例如vector<int> coll,持有int 类型的对象。如果我不知道 coll 是持有 int 怎么办(但我知道它是向量),我将如何查找类型信息?
【问题讨论】:
您可以从对象的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
【讨论】:
decltype 关键字)。跨度>
decltype 是新的 C++11 功能