Here is a minimal code that shows the problem:
template<typename To, typename From> To convert(const From& x);
struct A
{
int value;
template<typename T> A(const T& x) { value = convert<A>(x).value; }
};
struct B : public A { };
int main()
{
B b;
A a = b;
}
It gives me: undefined reference to 'A convert<A, B>(B const&)'
As expected, as I removed the default copy constructor. But if I add this line to A:
A(const A& x) { value = x.value; }
I get the same error. If I try to do this way: (adding a template specialization)
template<> A(const A& x) { value = x.value; }
I get: error: explicit specialization in non-namespace scope 'struct A'.
How to solve it?
My compiler is MinGW (GCC) 4.6.1
EDIT:
The convert functions converts from many types to A and back again. The problem is that don’t make sense writing a convert function from B to A because of the inheritance. If I remove the line that calls convert from A it just works. The idea is to call convert for all times that do’t inherit from A, for these, the default constructor should be enough.
As for as I understand, when
bis passed, asbis not an object ofA, copy constructor is not called, instead the template constructor is called.However, if an object of the derived class is passed, you want the copy constructor of
Ato be called.For this, there is one solution using
<type_traits>(c++0x):The template is disabled why an object of a class derived from
Ais passed, so the only available constructor is the copy constructor.