There are several questions on SO that relate to casting lambdas to std::function
s, but I have yet to see one that uses a parameter pack for the argument list.
Here is a solution that will let you call functor
without specifying it's template argument:
#include
#include
template struct Fun_trait {};
template
struct Fun_trait Ret>
{
using F = std::function Ret>;
};
template
void functor(std::function f) {}
template
std::void_t
functor(F f)
{
return functor::F>(f);
};
int main(int argc, char * argv[])
{
auto x = [] (int a, int b) { return a * b; };
// nice and easy:
functor(x);
return 0;
}
This is just a lazy first draft to get you started. You need to expand it to support forwarding and non-const operator()
.
It works in 2 stages:
1st we have Fun_trait
who - for pointer method types (e.g. the operator()
of a lambda) - has defined an alias F
for the required std::function
argument type.
Next we have a overload of your function functor
which via SFINAE with std::void_t
kicks in only for functors with a non-overloaded operator()
(e.g. a lambda) and then using the above trait calls the main function functor
with the correct template argument deduced.