【问题标题】:Adding additional template arguments to a method of a class which is already templated when defining out-of-line在定义外联时向已经模板化的类的方法添加额外的模板参数
【发布时间】:2021-01-28 23:15:55
【问题描述】:
template <typename T>
struct S {
    T myValue;

    S(T&);

    template <typename... Ts>
    S(Ts&&...);
};

假设我想定义被调用的方法外线 S(some, arguments, of, various, types),我将如何定义方法? 对于S(T&amp;),我只是这样做

template <typename T>
S<T>::S(T&){ /* code */ }

,但如果我尝试去做

template<typename T, typename... Ts>
S<T>::S(Ts&&...){ /* code */ }

然后它给了我一个错误:“模板重新声明中的模板参数太多”。 删除 , typename... Ts 会导致关于未定义 Ts 的错误。

当方法有额外的模板参数时,在类/结构之外编写方法主体的正确语法是什么?

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

    cppreference

    如果封闭类声明又是类模板,则当在类主体之外定义成员模板时,它需要两组模板参数:一组用于封闭类,另一组用于自身:

    template<typename T1>
    struct string {
        // member template function
        template<typename T2>
        int compare(const T2&);
        // constructors can be templates too
        template<typename T2>
        string(const std::basic_string<T2>& s) { /*...*/ }
    };
    // out of class definition of string<T1>::compare<T2> 
    template<typename T1> // for the enclosing class template
    template<typename T2> // for the member template
    int string<T1>::compare(const T2& s) { /* ... */ }
    

    所以你需要这样做

    template<typename T>
    template<typename... Ts>
    S<T>::S(Ts&&...){ /* code */ }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多