inheritance - C++ Avoiding redefinition of code that needs to return a polymorphic type -


i have set of classes (subclassa, subclassb, etc) inherit superclass. these classes have myriad of methods identical between subclasses, except return reference *this (a.k.a. subclassx&). return type can't deprecated superclass& either, because subclass-specific functions , members wouldn't accessible.

i'm looking short, clean way implement don't have replicate method code in each subclass.

the best thing i've been able come (pseudo-code), i'm not sure if work:

//methods.cpp subclass& general_method_1() {return *this;} subclass& general_method_2() {return *this;} 

and then:

#define subclass subclassa class subclassa : public superclass {      #include "methods.cpp"       subclassa& specific_method_1() {return *this;} }  #define subclass subclassb class subclassb : public superclass {      #include "methods.cpp"       subclassb& specific_method_2() {return *this;} } 

not mention seems kind of hackish , difficult interpret. ideas?

edit: should have mentioned need able polymorphically access subclasses through pointers superclass. example, following needs valid:

superclass* subclass[2]; subclass[0] = new subclassa; subclass[1] = new subclassb; 

crtp.

template <class derived> class base {     derived& derived() { return static_cast<derived&>(*this); } };  class derived1: public base<derived1> { };  class derived2: public base<derived2> { }; 

in order access things polymorphically, 1 needs split base in two:

class base {   public:     virtual ~base() {}     // virtual base& derived() = 0; -- note: not work! };  template <class derived> class baseimpl : public base {     derived& derived() { return static_cast<derived&>(*this); } };  class derived1: public baseimpl<derived1> { };  class derived2: public baseimpl<derived2> { };  int main() {     base* b[2] = { new derived1, new derived2 }; } 

Comments

Popular posts from this blog

php - render data via PDO::FETCH_FUNC vs loop -

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

The canvas has been tainted by cross-origin data in chrome only -