0

I know there are other questions on SO relating to std:tuple iteration, but I can't find one that seems to answer my requirement.

I have a templates class that has a tuple (it needs to be a container class holding objects passed in via variadic template parameters; all these are derived from a base class).

I want to have a series of member variable pointers that are set to point at the 1st, 2nd, 3rd etc elements of the tuple. There are a defined number of such member variables, so if there are too few tuple elements then the pointers should be null. If there are more tuple elements than member variables then there will simply be members of the tole that are not pointed to by such member variables.

class BaseTupleElement {
public:
    virtual int polymorphicFunction() {return 0;};  // can be overridden to avoid need for RTTI on embedded system
};

class DerivedElement1 : public BaseTupleElement {
public:
    virtual int polymorphicFunction() {return 1;};
}

class DerivedElement2 : public BaseTupleElement {
public:
    virtual int polymorphicFunction() {return 2;};
}

template<typename... systems>   // systems will always be of derived class of BaseTupleElement
class System {
    System();
    const std::tuple<systems...> subSystems;

    DerivedElement1 *pd1;
    DerivedElement2 *pd2;
};

template<typename... systems> System::System() : subSystems(systems{}...) {
    pd1 = NULL;
    pd2 = NULL;
    // I want to go through each item in the tuple and set pd1 & pd2 to point to the first element
    // that returns 1 or 2 respectively, then I can use pd1 & pd2 as derived pointers and utilise
    // full functionality of derived class

}

I've tried various incantations of std::get(BaseTupleElement) inside a for loop, with 0 <= i < std::tuple_size but I get compile errors like:

error: the value of 'i' is not usable in a constant expression

Is there an easy way to solve this please?

Otherwise my thinking is to do something like:

System() : subSystems{std::make_unique<systems>()...} {}
std::vector<std::unique_ptr<BaseTupleElement>> subsystemVector;

I'd prefer not to use dynamic allocation if I can get away with it (and certainly not RTTI), because it's on an embedded system.

Constructor
  • 7,273
  • 2
  • 24
  • 66
John
  • 10,837
  • 17
  • 78
  • 141
  • `error: the value of 'i' is not usable in a constant expression` Remember that you have to solve this at compile time. – πάντα ῥεῖ Jul 18 '14 at 14:14
  • Thanks - I just don't see how to do this at compile time and therefore be able to iterate through the tuple to set pointers to the elements of the tuple in order to get access to the derived class functionality of each tuple element. – John Jul 18 '14 at 16:14

0 Answers0