Reputation: 1531
I am trying to overload assignment operators for two different template classes but with the same template type:
template <class DataType> class Foo
{
public: Foo<data_type>& operator=(Bar<data_type> const &bar);
};
template <class DataType> class Bar
{
public: Bar<data_type>& operator=(Foo<data_type> const &foo);
};
However when I try:
Foo<int> a;
Bar<int> b = a;
I get the error:
No viable conversion from 'Foo< int >' to 'Bar< int >'.
How do I achieve this?
Upvotes: 0
Views: 1562
Reputation: 126412
When you write:
Bar<int> b = a; // ERROR! No viable user-defined conversion sequence
You are copy-initializing object b
from object a
. This is not the same as assigning object a
to an already constructed object b
, in spite of the =
symbol being used.
With copy-initialization, the compiler has to look for a user-defined conversion sequence that can convert a
into an object of type Bar<int>
, from which b
could be eventually copy-constructed or move-constructed.
Assignment, on the other hand, would work:
Foo<int> a;
Bar<int> b;
b = a; // OK
Upvotes: 1
Reputation: 263058
Conversions are done via copy constructors, not assignment operators. So you want to implement:
Bar(const Foo<data_type>& foo);
Upvotes: 1