Say I have a function that takes a variable number of parameters: I want to call this function from somewhere else, building the list of parameters, but without knowing in a
The easier way to do at runtime what the OP asked is probably by relying on standard containers like std::vector
s and the others.
Anyway, for the sake of completeness, here is an example of how a variadic pack of parameters can be created at compile time and used later to invoke a function:
#include
#include
#include
auto params(std::index_sequence<0>) {
return std::tuple{};
}
template
auto params(std::index_sequence) {
auto tup = std::tuple{ sizeof...(O) };
auto seq = std::make_index_sequence{};
return std::tuple_cat(tup, params(seq));
}
void foo() {
std::cout << "done." << std::endl;
}
template
void foo(Arg &&arg, Args&&... args) {
std::cout << "arg: " << arg << ", still to be elaborated: " << sizeof...(Args) << std::endl;
foo(std::forward(args)...);
}
template
void invoke(std::tuple &tup, std::index_sequence) {
foo(std::get(tup)...);
}
template
void bar(std::integral_constant size) {
auto seq = std::make_index_sequence{};
auto tup = params(seq);
invoke(tup, seq);
}
int main() {
bar(std::integral_constant{});
bar(std::integral_constant{});
}
Unfortunately, for it must be completely resolved at compile time, the argument for the bar
function cannot be a std::size_t
for itself.
Instead, a std::integral_constant
can be used to do that.