gexicide
gexicide

Reputation: 40048

Template constructor in template class must be defined in the class definition?

suppose I write a template class with a template constructor, like that.

template<typename T>
class X{


    template<typename S>
    X(X<S> x){}
};

compiles fine. However, when I try to define the constructor outside of the template declaration, like this:

template<typename T>
class X{


    template<typename S>
    X(X<S> x);
};


template<typename T, typename S>
X<T>::X(X<S> y){}

I receive the following error:

error: invalid use of incomplete type ‘class X<T>’

why? Is it not possible to define a template constructor of a template class outside of the class declaration?

Upvotes: 8

Views: 4249

Answers (3)

juanchopanza
juanchopanza

Reputation: 227370

Your class has a single template parameter, and you essentially have a template function inside of it, so you need

template<typename T>
template <typename S>
X<T>::X(X<S> y){}

Upvotes: 4

Bo Persson
Bo Persson

Reputation: 92211

You have two levels of templates, and have to specify them separately.

template<typename T>
template<typename S>
X<T>::X(X<S> y){}

Upvotes: 13

Torsten Robitzki
Torsten Robitzki

Reputation: 2555

Try this:

template<typename T>
template<typename S>
X<T>::X()( X<S> y )
{
}

Upvotes: 5

Related Questions