maple
maple

Reputation: 1894

How to get the element type in a nesting vector?

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.

Upvotes: 1

Views: 93

Answers (1)

T.C.
T.C.

Reputation: 137310

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> {}; 

You use it as, e.g.,

typename data_type<DataType>::type meow;
// type of 'meow' is int if DataType is vector<vector<int> >, or vector<int>, or int

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

Upvotes: 5

Related Questions