Ælex Ælex -4 years ago 122
C++ Question

template variadic function: arbitrary number of classes with arbitrary number of constructor parameters

I am unsure of what the proper name is, so far I comprehend the notion of using variadic template arguments (e.g., in comparison to


So let's assume there is an arbitrary number of classes
and an arbitrary number of parameters
which is dependant on each class

I know that I may construct any class
using a variadic template:

template <typename T, typename... Args>
void make_class(Args... args)
auto k = T(args...);

However I want to allow creation of multiple classes which are not of the same type and most likely have different
Furthermore, I want to iterate the classes
being constructed.
Something along the lines:

template <typename T, typename... Classes, typename Args>
void make_classes(Classes... classes)
for (auto type : classes) {
make_class<T>(args...); //???

  1. Is this possible?

  2. If not possible, are there any potential work-arounds?

  3. Is there a name for such a pattern/approach? Is this a

Apologies if this is a duplicate.

Answer Source

You'll need to delineate the arguments for each class by passing them in a tuple, since otherwise the result could be ambiguous for classes with more than one constructor (and note that most classes have at least a default constructor and copy constructor).

That done, this is easy to write:

template<class... Classes, class... Args>
void make_classes(Args&&... args) {
    auto k = std::tuple<Classes...>{


make_classes<std::pair<int, float>, std::string, std::vector<double>>(
    std::forward_as_tuple(42, 3.14f),
    std::forward_as_tuple(5, 99.99));


Note that make_from_tuple is a C++17 library addition; if your library doesn't have it you can copy the example implementation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download