hungry91
hungry91

Reputation: 132

c++: Two ways of declaring multiple templates

I have the following code:

template<typename T>
struct Pair3{
    T first, second;
    Pair3() : first(T()), second(T()) {}
    Pair3(T first, T second) : first(first), second(second) {}
    Pair3(const Pair3<T>& in) : first(in.first), second(in.second) {}
    template<typename U> void copyFrom(Pair3<U> in);
};

template<typename T>
template<typename U>
void Pair3<T>::copyFrom(Pair3<U> in){
    first = in.first;
    second = in.second;
}

why do I have to write

template<typename T>
template<typename U>

before copyFrom implementation and I can't write:

template<typename T, typename U>.

What would that mean? Why would that be wrong? Conversely: why can't I declare struct Pair3 like this:

  template<typename T, typename U>
    struct Pair3{
        T first, second;
        Pair3() : first(T()), second(T()) {}
        Pair3(T first, T second) : first(first), second(second) {}
        Pair3(const Pair3<T>& in) : first(in.first), second(in.second) {}
        void copyFrom(Pair3<U> in);
    };

or even:

template<typename T>
template<typename U>
    struct Pair3{
        T first, second;
        Pair3() : first(T()), second(T()) {}
        Pair3(T first, T second) : first(first), second(second) {}
        Pair3(const Pair3<T>& in) : first(in.first), second(in.second) {}
        void copyFrom(Pair3<U> in);
    };

Thanks!

Upvotes: 1

Views: 491

Answers (1)

Dimitrios Bouzas
Dimitrios Bouzas

Reputation: 42909

According to standard N4431 §14.5.2/1 Member templates [temp.mem] (Emphasis Mine):

A template can be declared within a class or class template; such a template is called a member template. A member template can be defined within or outside its class definition or class template definition. A member template of a class template that is defined outside of its class template definition shall be specified with the template-parameters of the class template followed by the template-parameters of the member template.

[Example:

template<class T> struct string {
template<class T2> int compare(const T2&);
template<class T2> string(const string<T2>& s) { /∗ ... ∗/ }
};
template<class T> template<class T2> int string<T>::compare(const T2& s) {
}

— end example ]

Defining as:

template<typename T, typename U>.

Would be wrong because this is not the way the C++ standard specifies how member templates of class templates should be defined outside the template class definition.

Upvotes: 1

Related Questions