Alexander Alexander - 2 years ago 82
C++ Question

Variadic template, function as argument

I would like to use a function as argument in a variadic template, why does the following not work? How do I make it work?

template<typename F, typename... Args>
F test(F f, const Args&&... args) {
return f(std::forward<Args>(args)...);

int simple(int i) {
return i;

int main()
std::cout << test(simple, 2); // error, 'std::forward': none of the 2 overloads could convert all the argument types

Answer Source

There are a couple of problems with your code.

First of all, you should use forwarding references, so you need to change const Args&&... to Args&&....

Then, test does not have to return F. So it is reasonable to use decltype(auto) here.

In addition to that, it makes sense to forward f too.

The fixed version might look like this:

template<typename F, typename... Args>
decltype(auto) test(F&& f, Args&&... args) {
    return std::forward<F>(f)(std::forward<Args>(args)...);


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download