It's often useful in C++ to work with lambdas and function objects, rather than function pointers. The reason being that a lambda's or function object's type fully encodes what is getting called (and thus allows inlining), whereas a function pointer's type merely encodes the signature. I had the interesting thought that it might be useful when using generic code to create a lambda that calls a given function. In other words, a higher order function that given a specified function, returns a lambda that calls it. To avoid any indirection, function pointer non-type template parameters have to be used. The problem is that to specify such a non-type template parameter, you have to know the signature of the function. I'm not able to get around needing to pass the function in question twice: once to deduce the types, and once to actually specialize on the function. My best attempt looks like this:
template <class T>
struct makeLambdaHelper;
template <class R, class ... Args>
struct makeLambdaHelper<R(*)(Args...)>
{
template <void(*F)(Args...)>
static auto blah() {
return [] (Args && ... args) {
return F(std::forward<Args>(args)...);
};
}
};
To use this, you would do:
void f(int, int) { std::cerr << "f\n"; };
...
auto lam = makeLambdaHelper<decltype(&f)>::blah<f>();
lam(0,0);
When f's type is passed as the template argument to makeLambdaHelper, first its signature is deduced. Then the struct has a static function that declares a non-type template parameter; so we pass f itself, and get out a lambda. Having to pass f twice like this is pretty ugly; is it possible to do better, maybe by doing something clever with default template parameters?