c++ - Multiple inheritance via templates -


is idea replace virtual multiple inheritance (diamon) teplates inheritence (linear)? example have class diagram :

       ibase     /          \    /            \ iextendedbase  baseimpl   \            /    extendedimpl 

i know can implement virtual inheritance. can use templates in order make diagram linear?

class ibase     {     public:         virtual std::string name() = 0;     };      template<typename t>     class baseimpl : public t     {     public:         virtual std::string name() override         {             return "basecommonimpl";         }     };      template<typename t>     class iextendedbase : public t     {     public:         virtual std::string extended_name() = 0;     };      template<typename t>     class extendedbaseimpl : public t     {     public:         virtual std::string extended_name() override         {             return "extendedbaseimpl";         }     }; 

now typedef can specialize extendedbase

typedef iextendedbase<baseimpl<ibase>> _extendedbase; typedef extendedbaseimpl<_extendedbase> _extendedbaseimpl; 

which method better? virtual inheritance or template inheritance?

while can obtain similar results using these 2 different approaches (multiple inheritance vs. template), there important semantic differences.

unfortunately, not give enough information recommend objective choice. here considerations:

multiple inheritance approach

multiple inheritance meant enforcing effective separation of concerns.

this approach should preferred if in case extendedimpl is-a iextendbase , simulatneously is-a baseimpl, both inheritance relations independent.

it has inconvenience of slight performance overhead in cases (casting example).

but has advantage of allowing extendedimpl used of bases used. , in addition, allows dynamic, runtime based polymorphism (if of base has virtual member function).

enter image description here

template approach

templates meant generic programming. approach prefereed if extendedimpl generic, , "bases" more parameters generic concept, rather concept extended further.

template have here approach of better performance (single inheritance). don't implement original concept of initial schema. , don't have flexibility of dynamic polymorphism.

enter image description here

if relation between types not of generic nature, might induce here undesired dependencies. example here, iextendedbase inherit baseimpl. ok in many cases. unnatural in other cases, leading lasting desing issues in maintenance phase.

conclusion

now it's decide advantage , inconvenience fits best specific case. if needed, edit question giving more precise indication context , intentions, , i'll adapt answer accordingly.


Comments