Reputation: 3582
Imagine I create a class with a template constructor to define implementations later:
struct A {
template<typename T>
A(const T& arg);
};
How can I avoid overriding compiler's implicitly generated copy constructor A(const A&)
? In C++11 I can do something like
#include <type_traits>
struct A {
template<typename T, class =
typename std::enable_if<std::is_same<A, T>::value>::type>
A(const T& arg);
};
and it works. But C++03 doesn't support default template arguments. Any workaround here?
Upvotes: 1
Views: 236
Reputation: 227468
You don't need to do anything. The compiler generated coppy constructor will kick in as needed. A copy constructor cannot be a template. For example,
#include <iostream>
struct A {
template<typename T>
A(const T& arg) { std::cout << "template\n"; }
};
int main()
{
A a(42); // template ctor
A b(a); // copy ctor
A c = b; // copy ctor
}
Output:
template
Upvotes: 3
Reputation: 72044
You shouldn't need one. The constructor in question will instantiate to A(const A&)
when given an A
, which is the same as the actual copy constructor, so the non-template constructor will be preferred.
Upvotes: 1