Using multiple overloads of a function in variadic template

52 Views Asked by At

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?

2

There are 2 best solutions below

0
Jarod42 On BEST ANSWER

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

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

Demo

0
KamilCuk On

Use a class. Overload on function members.

struct Fclass {
    double operator()(double x){
        return x * x;
    }
    int operator()(int x) {
        return x*x;
    }
};

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

int main() {
    fnc(Fclass(), 1, 2, 3.5);
}