Ælex Ælex - 3 months ago 10
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

std::initializer_list
).

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

I know that I may construct any class
k
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
Args
.
Furthermore, I want to iterate the classes
k
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
    parameter_pack
    ?



Apologies if this is a duplicate.

Answer

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...>{
        std::make_from_tuple<Classes>(std::forward<Args>(args))...};
}

Usage:

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

Example.

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

Comments