Consider the following example:
using function_pair = std::pair<int, void(*)(void*)>; // This line cannot change
template <class Arg, class F>
function_pair make_function_pair(int i, F&& f)
{
return function_pair(i,
[&](void* x){std::forward<F>(f)(static_cast<Arg*>(x));}); // Not working
}
// Later in code
auto p1 = make_function_pair<char>(1, [](char* x){std::cout<<*x<<std::endl;});
auto p2 = make_function_pair<double>(2, [](double* x){*x = *x*2;});
auto p3 = make_function_pair<float>(3, [](float* x){*x = *x*3;});
The code fails to compile because of the capturing lambda (when the lambda does not have to capture f, it works). I am wondering how to make this work without using std::function, because the computing overhead of std::function is huge and I cannot afford that. And even without this practical reason, I am wondering how to solve this "academic" problem without using std::function.
autofor the function return type and you avoid the overhead ofstd::functionstd::function? I doubt it, because you are also capturing by reference, and capturing by reference is a big no-no when you are returning a copy of the lambda from the current scope. The overhead of astd::functionis larger than a function pointer, but it isn't ridiculously more if you fall within the small function optimization size.void(char*)tovoid(void*)is undefined behavior.