问题
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...); //???
}
}
- Is this possible?
- If not possible, are there any potential work-arounds?
- Is there a name for such a pattern/approach? Is this a
parameter_pack
?
Apologies if this is a duplicate.
回答1:
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.
来源:https://stackoverflow.com/questions/39168220/template-variadic-function-arbitrary-number-of-classes-with-arbitrary-number-of