I have a template class A. What I want to do is to write a copy constructor between A with template T1 and A with template T2. How do I solve this? Here is some example code from the struct header:
template <typename T>
struct A {
A(const A<T>& other); // copy from same type T
template <typename T2>
A(const A<T2>& other); // copy from different type T2
}
How would I go about to implement this in a .cpp file?
EDIT: What I really meant was: "How would I go about to implement this outside the class definition?" (a syntax problem)
-
templates go in header files463035818_is_not_an_ai– 463035818_is_not_an_ai2015年10月28日 14:05:48 +00:00Commented Oct 28, 2015 at 14:05
-
of course! What I meant was "How would I go about to implement this outside the class definition?"Myone– Myone2015年10月28日 14:23:56 +00:00Commented Oct 28, 2015 at 14:23
3 Answers 3
The syntax for defining a template member function of a template class is not immediately obvious. You need to have two template parameter lists; one for the class and one for the function:
template <typename T> //class template parameters
template <typename T2> //function template parameters
A<T>::A (const A<T2>& other) {
//...
}
Note that templates need to be implemented in the header file, so you can't put this in the .cpp.
Comments
You cannot define template function in .cpp file. But in header, outside of class definition you can just
template<typename T>
template<typename T2>
A<T>::A(const A<T2&>& other)
{
// implementation
}
Comments
You could make that other constructor a template itself:
template< class T > class A
{
public:
A()
{
}
A(const A<T> & other)
{
cout << "T" << endl;
}
template<class T1> A(const A<T1> & other)
{
cout << "T1" << endl;
}
};
int main()
{
A<int> a1;
A<int> a2 = a1; // prints "T"
A<double> a3 = a1; // prints "T1"
return 0;
}