4

Suppose I have a class of a variable:

class Variable
{
  const std::string name;
  const double scale;

public:
  Variable(const std::string& _name, double _scale) : name(_name), scale(_scale) { }
};

Now I define a class of a system containing variables:

template<class... T>
class System
{
 std::tuple<T...> variables;

public:
 System(???) : ??? { }
};

How can I define the constructor of the System that will somehow pass its agruments to variables to initialize each of them? I would like to be able to write something like this:

class VAR1 : public Variable { };
class VAR2 : public Variable { };

System<VAR1, VAR2> s{ /* init values: ("VAR1", 10), ("VAR2", 20) */};
Evg
  • 25,259
  • 5
  • 41
  • 83

1 Answers1

5

Assuming you have the correct constructors in the derived class:

template<class... T>
class System
{
    std::tuple<T...> variables;
public:
    System(const T&... t) : variables(t...) { }
};

System<VAR1, VAR2> s({"VAR1", 10}, {"VAR2", 20});
Weak to Enuma Elish
  • 4,622
  • 3
  • 24
  • 36
  • Thank you for the answer. Now I see that I should reconsider the initial idea because I don't want to define (identical) constructors in each derived class: I wanted to use derived classes as mere tags to discern different variables by types (playing roles of names) instead of numbers in `std::get<...>`. – Evg Mar 10 '16 at 20:41
  • @Evgeny Putting `using Variable::Variable;` in the derived classes allows it to be initialized this way too. – Weak to Enuma Elish Mar 10 '16 at 20:43
  • This code is not compiling you need to change variables(t...) – PapaDiHatti May 12 '17 at 10:58
  • @Kapil Nice spot, thank you! Can't believe I forgot something so obvious. – Weak to Enuma Elish May 12 '17 at 12:41