I am trying to match callable objects in C++ templates and provide different implementations based on the type of callable object that is receives as an argument.
I have the following template functions:
template<class Ret, class... Args>
void fun(std::function<Ret(Args...)> f) {}
template<class Ret, class... Args>
void fun(Ret(*f)(Args...)) {}
They accept std::function
objects and ordinary function pointers, and correctly deduce their return Ret
and argument Args
types. However, I am having difficulty passing anonymous lambda expressions as they do not match any of the templates above.
Calling something like
fun([](int x, int y){return x + y;})
results in a compilation error. What is the correct way to implement a template expression that accepts anonymous lambda functions? Maybe one way is to check if the class that is being passed has an operator()
method?