【问题标题】:Provide definition of constructor template outside a class template在类模板之外提供构造函数模板的定义
【发布时间】: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 的目的)

  1. 如何在类外正确定义此构造函数。
  2. 这样的模式(类模板参数与构造函数模板参数不同)是否有任何实际用途?举个例子会很有帮助。

【问题讨论】:

  • 你试过了吗:template &lt;class T&gt; template &lt;typename S&gt; C&lt;T&gt;::C(const S&amp;) { /* ... */}

标签: c++ class c++11 templates constructor


【解决方案1】:

正确的语法是:

template <class T>
template <class S>
C<T>::C(const S& str)
{
    // ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 2012-08-14
    • 1970-01-01
    相关资源
    最近更新 更多