Evg
Evg

Reputation: 26292

Initialize tuple member in constructor of variadic template class

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) */};

Upvotes: 5

Views: 2084

Answers (1)

Weak to Enuma Elish
Weak to Enuma Elish

Reputation: 4637

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});

Upvotes: 6

Related Questions