Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

c++ - Adding additional template arguments to a method of a class which is already templated when defining out-of-line

template <typename T>
struct S {
    T myValue;

    S(T&);

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

Suppose I wanted to define methods out-of-line to be called like S(some, arguments, of, various, types), how would I define the methods? For S(T&), I just do

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

, but If I try and do

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

then it gives me an error: 'too many template parameters in template redeclaration'. Removing , typename... Ts results in an error about Ts not being defined.

What is the correct syntax to write the body of a method outside of the class/struct when there are additional template arguments for the method?

question from:https://stackoverflow.com/questions/65935185/adding-additional-template-arguments-to-a-method-of-a-class-which-is-already-tem

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Per cppreference,

If the enclosing class declaration is, in turn, a class template, when a member template is defined outside of the class body, it takes two sets of template parameters: one for the enclosing class, and another one for itself:

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) { /* ... */ }

So you would need to do

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...