Grandparent constructor call with inheritance pattern

I decided to use template inheritance to avoid multiple and virtual inheritance. My goal is to make different children (4 or 5 generations or inheritance, which I do not control) have a common function call no matter what they receive.

My solution inserts template inheritance like this:

template <typename BASE> class common_call : public BASE { public: void foo() { /*implementation independent of base*/ } }; class child1 : public common_call <base1> {}; class child2 : public common_call <base2> {}; 

There is a problem calling the base constructor. The base1 and base2 classes (not written by me) have different constructors that I have to call in the initialization list. The common_call pattern knows nothing about these constructors, but child classes do as they are currently directly inherited.

Do I have a way to do this:

 class child3 : public common_call<base3>{ public: child3(param1, param2) : base3(param2) {/*do things here*/} }; 

I try to avoid creating specialized specialized templates for each type of database, if possible.

+4
source share
1 answer

If you give a common_call template constructor using variation patterns such as this:

 template <typename BASE> class common_call : public BASE { public: // C++11 variadic templates to define whole range of constructors template<typename... Args> common_call(Args&&... args) : BASE(std::forward<Args>(args)...) {} void foo() { /*implementation independent of base*/ } }; 

you can get any template argument from common_call (e.g. base3 ) and call any constructor that this class defines

 class child3 : public common_call<base3> { public: child3(Type1 param1, Type2 param2) : common_call(param2), // call constructor overload with 1 parameter of Type2 t1_(param1) // initialize t1_ member {} private: Type1 t1_; }; 
+2
source

Source: https://habr.com/ru/post/1434971/


All Articles