0

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?

1
  • Note that the given example fails with multiple compile errors long before it gets to the conversion issue. Commented Apr 28, 2013 at 19:17

2 Answers 2

1

Conversions are done via copy constructors, not assignment operators. So you want to implement:

Bar(const Foo<data_type>& foo);
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

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.