c++ - Accepting lambda as function parameter and extracting return type -
this question has answer here:
i need accept lambda function parameter , figure out return type. far, couldn't come workable. here example:
template <typename t1, typename t2> t1 foo(t2 arg, std::function<t1(t2)> f) { return f(arg); } ... int n = foo(3, [](int a){ return + 2; }); <-- error!
how can done? boost solution ok, too.
you shouldn't pass std::function
parameter. has overhead because uses type erasure store type of callable, such function pointers, functors, lambdas (which automatically generated functor), etc. instead, should template function type. can use trailing return type figure out return type of function:
template <typename t, typename function> auto foo(t arg, function f) -> decltype(f(arg)) { return f(arg); }
Comments
Post a Comment