1

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)

asked Oct 28, 2015 at 14:04
2
  • templates go in header files Commented Oct 28, 2015 at 14:05
  • of course! What I meant was "How would I go about to implement this outside the class definition?" Commented Oct 28, 2015 at 14:23

3 Answers 3

4

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.

answered Oct 28, 2015 at 14:07
Sign up to request clarification or add additional context in comments.

Comments

2

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
}
answered Oct 28, 2015 at 14:06

Comments

1

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;
}
answered Oct 28, 2015 at 14:07

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.