Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CRTP and default assignment operator

In the following :

template<typename Derived>
class Base:
{
    inline Derived& operator=(const Base<Derived>& x);
}

Does this declaration erases the default copy assignment operator or do I have two operators :

inline Derived& operator=(const Base<Derived>& x); 
// (declared by me)

AND

inline Base<Derived>& operator=(const Base<Derived>& x); 
// (declared by the compiler)

In this case, when I call the function, how the compiler will get the right operator ?

like image 290
Vincent Avatar asked Sep 03 '26 18:09

Vincent


1 Answers

If you declare any method that can pass for an assignment operator:

XXX Foo::operator=(Foo&);
XXX Foo::operator=(Foo const&);
XXX Foo::operator=(Foo volatile&);
XXX Foo::operator=(Foo const volatile&);

then the compiler will not generate the default version Foo& operator=(Foo const&);.

Note that the return type is completely free, as for other methods. You could use void, bool, whatever really. It is just idiomatic (but not required) to return a reference to self in order to allow assignment chaining: a = b = c = 0; which itself stems from the guideline that overloaded operators should follow the semantics of their built-in counterparts.

like image 178
Matthieu M. Avatar answered Sep 05 '26 06:09

Matthieu M.