我有一个数据类型供用户定义,它可以是int, vector<int>, vector<vector<int> >
...我想知道是否有一些模板技巧来获取类型 int?我更喜欢使用 none c++11 方法,因为我的 g++ 版本是 4.1.2,我无法更新它。
最佳答案
这适用于 GCC 4.3,这是我可以轻松访问的最早版本的 GCC。您必须测试它是否适用于 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
这使用 the void_t
trick并处理定义 value_type
的所有内容类型定义。好处是它开箱即用 std::vector<std::deque<std::list<int> > >
;缺点是它可能太多了( data_type<std::vector<std::string> >::type
是 char
)。
如果你只想让它与 vector 一起工作,你可以这样做:
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
关于c++ - 如何获取嵌套 vector 中的元素类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35616215/