How to get the data type in a vector using template?

Viewed 68

I'm writing a function template like this:

template <class T>
class MyClass() {}

template <typename A, typename B>
auto func(A<B>& data) {
    return MyClass<B>();
}

So I can using the function like this:

vector<int> vi;    auto a = func(vi);
vector<string> vs;    auto b = func(vs);
list<int> li;    auto c = func(li);
list<string> ls;    auto d = func(ls);

But obviously it's not allowed. How should I write a template to reach my goal?

2 Answers

You can declare A as template template parameter, otherwise you can't use it as A<B> in the function parameter declaration since it's not considered as template.

template <template <typename...> class A, typename B>
auto func(A<B>& data) {
    // ... use B as the data type ...
}

Another way is STL containers (including std::vector and std::list) have a member type as value_type, you can use it as

template <typename A>
auto func(A& data) {
    using B = typename A::value_type;
    // ... use B as the data type ...
}

This should work:

template <class T>
class MyClass {};

template <template <typename, typename...> typename A, typename B, typename ... REST>
auto func(A<B,REST...>& data) {
    return MyClass<B>();
}
Related