C++这样的模板构造函数

C++ template constructor like these

本文关键字:构造函数 C++      更新时间:2023-10-16

我如何为这些构造函数调用为我的类定义构造函数:

MyClass<std::list<int>, int> myClass1;
 MyClass<std::deque<std::string>, std::string> myClass2;
 MyClass<std::vector<char>, char> myClass3;

我知道会不会是:

MyClass<int> myClass1;

我想:

template <typename T>
class MyClass{
//...
};

但是如何使用模板添加整个集合?

要获得您要求的内容,您只需添加另一个模板参数:

template <typename Cont, typename T>
class SetSequence {
  //...
};

它需要带一个容器并不重要。容器类型与模板参数一样有效int

如果 T 参数始终是 Cont 的值类型,您可以通过只有一个模板参数来简化这一点。然后,您可以使用Cont::value_type来引用其元素的类型。

尝试使用可选的模板参数:

template<typename T , typename VALUE_TYPE = typename T::value_type>
struct SetSecuence
{
  ...
};

但是,您可以简单地将容器的值类型存储为成员 typedef:

template<typename T>
struct SetSecuence
{
  using value_type = typename T::value_type;
};

如您所见,这有效:

using secuence_type_1 = SetSecuence<std::vector<int>>;
using secuence_type_2 = SetSecuence<std::list<bool>>;
secuence_type_1 secuence;
typename secuence_type_1::value_type an_element_of_that_secuence;