Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functions as arguments of variadic templates

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?

like image 942
DLunin Avatar asked Oct 09 '14 08:10

DLunin


People also ask

How do you use Variadic arguments?

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.

How do you write a variadic function in C++?

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.

What is Variadic template in C++?

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.

What are Variadic functions Python?

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.


1 Answers

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.

like image 128
Jarod42 Avatar answered Oct 12 '22 22:10

Jarod42