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

Sun*_*tar 3 c++ templates stl

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>();
}
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

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

son*_*yao 6

您可以声明A模板模板参数,否则您不能像A<B>在函数参数声明中那样使用它,因为它不被视为模板。

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

另一种方法是 STL 容器(包括std::vectorstd::list)具有成员类型 as value_type,您可以将其用作

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