inheritance - operator= and functions that are not inherited in C++? -
until test i've made, believed constructors not inherited in c++. apparently, assignment operator=
not too...
- what reason of ?
- is there workaround inherit assignment operator ?
- is case
operator+=
,operator-=
, ... ? - are other functions (apart constructors/operator=) inherited ?
in fact, encountered problem doing crtp :
template<class crtp> class base { inline crtp& operator=(const base<crtp>& rhs) {/*something*/; return static_cast<crtp&>(*this);} }; class derived1 : public base<derived1> { }; class derived2 : public base<derived2> { };
is there solution working ?
edit : ok, have isolated problem. why following isn't working ? how solve problem ?
#include <iostream> #include <type_traits> // base class template<template<typename, unsigned int> class crtp, typename t, unsigned int n> class base { // cast base public: inline base<crtp, t, n>& operator()() { return *this; } // operator = public: template<typename t0, class = typename std::enable_if<std::is_convertible<t0, t>::value>::type> inline crtp<t, n>& operator=(const t0& rhs) { (unsigned int = 0; < n; ++i) { _data[i] = rhs; } return static_cast<crtp<t, n>&>(*this); } // data members protected: t _data[n]; }; // derived class template<typename t, unsigned int n> class derived : public base<derived, t, n> { }; // main int main() { derived<double, 3> x; x() = 3; // <- ok x = 3; // <- error: no match 'operator=' in ' x=3 ' return 0; }
the assignment operator technically inherited; however, hidden explicitly or implicitly defined assignment operator derived class (see comments below).
(13.5.3 assignment) assignment operator shall implemented non-static member function 1 parameter. because copy assignment operator
operator=
implicitly declared a class if not declared user, base class assignment operator hidden copy assignment operator of derived class.
you can implement dummy assignment operator forwards call base class operator=
, this:
// derived class template<typename t, unsigned int n> class derived : public base<derived, t, n> { public: template<typename t0, class = typename std::enable_if<std::is_convertible<t0, t>::value>::type> inline derived& operator=(const t0& rhs) { return base<derived, t, n>::operator=(rhs); } };
Comments
Post a Comment