Home > Blockchain >  Variadic template constructor to fill internal vector of std::variant
Variadic template constructor to fill internal vector of std::variant

Time:09-24

I got the following class

class A {
  std::string name;
  std::vector<std::variant<int,float>> data; 
};

my goal is to have a constructor to fill this class with variable number of argument. Examples

A("hello", 1, 2.0, 1)
A("hello", 1, 2.0, 1.2)
....

I tried something like

 template <typename... ARGS>
A(std::string n, ARGS... arguments) : name(n), data({arguments...}) {}

But the compiler complains that non-constant-expression cannot be narrowed from type 'float' to 'std::vector::size_type' in initializer list.

CodePudding user response:

You trying to call the constructor of data a bunch of times in the initializer list. Remember that variadic templates are unfolded at compile time. You will likely need to handle this outside the initializer list. Something like:

template <typename... ARGS>
A(std::string n, ARGS... arguments) : name(n) {
    data.reserve(sizeof...(T));
    (data.emplace_back(arguments), ...);
}

Assuming you have fold expressions (AKA c 17). Here is a live example. As a further note, your variant should be a double, or you should specify your input with 2.0f to avoid a narrowing conversion.

  • Related