【发布时间】:2022-07-22 21:18:09
【问题描述】:
考虑以下带有构造函数模板的类模板:
template <class T>
class C{
public:
T val_;
std::string str_;
template <typename S>
C(const S& str);
// C(const S& str) : str_(str) {}; // Valid definition of constructor within class body
void print(){std::cout << str_;}
};
然而,我试图在类之外定义构造函数,但我似乎无法找到一种方法来解释 S 类型。
template <typename T, typename S> // incorrect as too many parameters
C<T>::C(const S& str) : str_(str) {};
或者,我尝试过
template <typename T>
C<T>::C(const std::string& str) : str_(str) {};
这也不起作用(并且可能违背了S 的目的)
- 如何在类外正确定义此构造函数。
- 这样的模式(类模板参数与构造函数模板参数不同)是否有任何实际用途?举个例子会很有帮助。
【问题讨论】:
-
你试过了吗:
template <class T> template <typename S> C<T>::C(const S&) { /* ... */}?
标签: c++ class c++11 templates constructor