How to dynamic initialize multiple inheritance with variadic templates?

Viewed 46

I'm struggling with dynamic initialization of multiple inheritance with variadic templates.

This is my code so far:

#include <iostream>
#include <memory>

class BASE {
protected:
    int m_counter;
public:
    void StartCounter() {m_counter = 0;}
    void ShowCounter() {std::cout << "counter: " << m_counter << "\n";}
};

class C1 : virtual public BASE {
public:
    void Increase() {m_counter++;};
};

class C2 : virtual public BASE {
public:
    void Increase() {m_counter++;};
};

class C3 : virtual public BASE {
public:
    void Increase() {m_counter++;};
};

template<class... T>
class C4 : virtual public T... {
public:
    void Me() {std::cout << "C4\n";};
};

template<class... T>
std::shared_ptr<C4<T...>> gl_pointer(nullptr);

int main() 
  {
    bool use_c1 = false;
    bool use_c2 = true;
    bool use_c3 = true;
    
    // how to dynamic initialize the shared pointer?
    gl_pointer<C1,C2,C3> = std::make_shared<C4<C1,C2,C3>>();
    auto strategy = gl_pointer<C1,C2,C3>;

    //
    strategy->C4::StartCounter();
    if(use_c1) strategy->C1::Increase();
    if(use_c2) strategy->C2::Increase();
    if(use_c3) strategy->C3::Increase();
    strategy->C3::ShowCounter();
    
    //
    return 0;
  }

The code above compiles and works under Linux/g++. However, it's somehow limited, as I need to set manually which classes will be used.

Ideally the initialization would follow some basic rules, like:

if(use_c1)
  {
   gl_pointer<C1> = std::make_shared<C4<C1>>();
  }

or, for instance,

if(use_c2 && use_c3)
  {
   gl_pointer<C2,C3> = std::make_shared<C4<C2,C3>>();
  }

As said, I'm able to manually initialize the global shared_pointer. However, I would like to be able at runtime to choose which derived classes should be used by C4.

Is there any way to do this? Any advice?

Thanks in advance!

0 Answers
Related