Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor arguments from tuple

Suppose I have a template which is parametrized by a class type and a number of argument types. a set of arguments matching these types are stored in a tuple. How can one pass these to a constructor of the class type?

In almost C++11 code:

template<typename T, typename... Args>
struct foo {
  tuple<Args...> args;
  T gen() { return T(get<0>(args), get<1>(args), ...); }
};

How can the ... in the constructor call be filled without fixing the length?

I guess I could come up with some complicated mechanism of recursive template calls which does this, but I can't believe that I'm the first to want this, so I guess there will be ready-to-use solutions to this out there, perhaps even in the standard libraries.

like image 396
MvG Avatar asked Feb 15 '13 15:02

MvG


Video Answer


1 Answers

C++17 has std::make_from_tuple for this:

template <typename T, typename... Args>
struct foo
{
  std::tuple<Args...> args;
  T gen() { return std::make_from_tuple<T>(args); }
};
like image 50
panik Avatar answered Oct 09 '22 10:10

panik