Search code examples
c++variadic-templatesfunction-parameter

Using multiple overloads of a function in variadic template


I would like to pass an overloaded function as an argument for a variadic template function. I understand how to do it with one particular function (using static_cast). However, I am wondering if there is a way to use multiple functions of the same name in a variadic template.

This piece of code illustrates what I mean.

double f(double x){
    return x*x;
}
int f(int x){
    return x*x;
}

template<typename ... T>
bool fnc(foo,T...args){
    return (foo(args)+...);
}

And I would like to write

fnc(f,1,2,3.5);

Is there an elegant way to achieve that without using template recursion?


Solution

  • You might wrap the functions into a generic lambda (C++14):

    fnc([](const auto& e){ return f(e);}, 1, 2, 3.5);
    

    Demo