0

I'm currently trying to expand the following code. I have a number of classes (here A and B) with a common Interface class. I then combine the classes in one Collection class, which currently inherits from one or two of the classes.

I'm now trying to extend the Collection class template to support not just one or two classes but N classes. Is there any possibility to extend the template to support N classes?

I tried the version CollectionN, but I don't get the init function to run like this.

Thanks for any ideas and comments.

#include <iostream>

class Interface
{
public:
  virtual ~Interface() = default;
  virtual void init() = 0;
};

class A: public Interface
{
public:
  void init() override
  {
    std::cout << "init A\n";
  }

  void runA()
  {
    std::cout << "run A\n";
  }
};

class B: public Interface
{
public:
  void init() override
  {
    std::cout << "init B\n";
  }

  void runB()
  {
    std::cout << "run B\n";
  }
};

struct NullType { void init() {}};

// how to expand this to N possible classes like
template<class C1, class C2 = NullType>
class Collection: public C1, public C2
{
public:
  Collection()
  {
    std::cout << "create Collection\n";
    C1::init();
    C2::init();
    // init classes C3...CN
  }

};

template<class ... CN>
class CollectionN: public CN...
{
public:
  CollectionN()
  {
    std::cout << "create Collection\n";
    // CN...::init();  // any way to call init of all classes?
  }
};


int main(int argc, char const *argv[])
{
  std::cout << "collection\n";

  Collection<A, B> collectionAB;
  Collection<B> collectionB;
  // what i'm trying to do
  // Collection<A,B,C> collectionABC;
  return 0;
}
Rolf Lussi
  • 615
  • 5
  • 16
  • Multiple Inheritance is very taboo now-a-days, the Diamond of Death problem became a big issue. Are you positively sure you really need to use multiple inheritance? – Katianie Feb 02 '18 at 14:18
  • 1
    `int dummy[] = {0, (CN::init(), void(), 0)...};` solved my problem, thanks – Rolf Lussi Feb 02 '18 at 14:30

0 Answers0