c++ - 如何使用模板获取矢量中的数据类型?
我正在写一个这样的函数模板。
template <class T>
class MyClass() {}
template <typename A, typename B>
auto func(A<B>& data) {
return MyClass<B>();
}
所以我可以用这样的函数
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);
但显然是不允许的 我应该怎么写模板才能达到我的目标?
【回答】:
你可以声明 A
作为 模板模板参数,否则你就不能把它当作 A<B>
在函数参数声明中,因为它不被认为是模板。
template <template <typename...> class A, typename B>
auto func(A<B>& data) {
// ... use B as the data type ...
}
另一种方式是STL容器(包括 std::vector
和 std::list
)的成员类型为 value_type
您可以将其作为
template <typename A>
auto func(A& data) {
using B = typename A::value_type;
// ... use B as the data type ...
}
【回答】:这应该可以。
template <class T>
class MyClass {};
template <template <typename, typename...> typename A, typename B, typename ... REST>
auto func(A<B,REST...>& data) {
return MyClass<B>();
}