Suppose we have a class
template <int(*F)(int, int)>
class A {
// ...
};
It takes a function as a template argument.
Now I want to make a variadic template, which takes functions as template parameters.
template <int(*F...)(int, int)> // this won't compile
template <int(*F)(int, int)...> // this won't compile either
How to do it properly?
It takes one fixed argument and then any number of arguments can be passed. The variadic function consists of at least one fixed variable and then an ellipsis(…) as the last parameter. This enables access to variadic function arguments. *argN* is the last fixed argument in the variadic function.
Variadic functions are functions (e.g. std::printf) which take a variable number of arguments. To declare a variadic function, an ellipsis appears after the list of parameters, e.g. int printf(const char* format...);, which may be preceded by an optional comma.
A variadic template is a class or function template that supports an arbitrary number of arguments. This mechanism is especially useful to C++ library developers: You can apply it to both class templates and function templates, and thereby provide a wide range of type-safe and non-trivial functionality and flexibility.
Variadic parameters (Variable Length argument) are Python's solution to that problem. A Variadic Parameter accepts arbitrary arguments and collects them into a data structure without raising an error for unmatched parameters numbers.
You may do
using Function_t = int(*)(int, int);
template <Function_t ... Fs> struct s{};
else, if you don't want to use typedef
template <int(*...Fs)(int, int)> struct s{};
Note: the second version can't be anonymous (Fs
is required) as ISO C++11 requires a parenthesized pack declaration to have a name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With