如何获取嵌套向量中的元素类型? [英] How to get the element type in a nesting vector?
问题描述
我有一个DataType供用户定义,它可以是int, vector
... 我想知道是否有一些模板技巧来获取int类型?我更喜欢使用 none c++11 方法,因为我的 g++ 版本是 4.1.2,我无法更新它.
I have a DataType for user to define, it can be int, vector<int>, vector<vector<int> >
... I want to know whether there are some template tricks to get the type int? I prefer to use a none c++11 method because my g++ version is 4.1.2 and I can not update it.
推荐答案
这适用于 GCC 4.3,这是我可以轻松访问的最早版本的 GCC.您必须测试它是否适用于 4.1.2.
This works on GCC 4.3, which is the earliest version of GCC I have easy access to. You'll have to test if it works with 4.1.2.
template<class T> struct voider { typedef void type; };
template<class T, class = void>
struct data_type {
typedef T type;
};
template<class T>
struct data_type<T, typename voider<typename T::value_type>::type>
: data_type<typename T::value_type> {};
您将其用作例如
typename data_type<DataType>::type meow;
// type of 'meow' is int if DataType is vector<vector<int> >, or vector<int>, or int
这使用 void_t
技巧 并与定义 value_type
类型定义的所有内容.好处是它对 std::vector<std::deque<std::list<int> 开箱即用.>>
;缺点是它可能太多了(data_type
是 char
).
This uses the void_t
trick and works with everything that defines a value_type
typedef. The benefit is that it works out of the box for std::vector<std::deque<std::list<int> > >
; the drawback is that it might be too much (data_type<std::vector<std::string> >::type
is char
).
如果你只是想让它与向量一起工作,你可以这样做:
If you just want it to work with vectors, you can do:
template<class T>
struct data_type {
typedef T type;
};
template<class T, class A>
struct data_type<std::vector<T, A> >
: data_type<T> { };
// partially specialize for other containers if wanted
这篇关于如何获取嵌套向量中的元素类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!