The Question
I have a number of C++ functions void f()
, R g(T a)
, S h(U a, V b)
and so on. I want to write a template function that accepts f
, g
, h
and so on as a template argument and calls that function.
ie I want something like this:
template<MagicStuff, WrappedFunction>
ReturnType wrapper(MagicallyCorrectParams... params)
{
extra_processing(); // Extra stuff that the wrapper adds
return WrappedFunction(params);
}
...
wrapper<f>(); // calls f
wrapper<g>(T()); // calls g
wrapper<h>(U(), V()); // calls h
Here's what I've tried so far:
Solution 1
template<typename ReturnType, typename Args...>
ReturnType wrapper(ReturnType (*wrappee)(Args...), Args... args)
{
extra_processing();
return wrappee(args...);
}
...
wrapper(f); // calls f OK
wrapper(g, T()); // calls g OK
wrapper(h, U(), V()); // calls h OK
This works but is unsatisfactory because in my case, I want the function pointer bound to the template instance. The function pointer is determinable statically at compile time and it is not desirable in my use case to have to pass it as a parameter at runtime.
Solution 2
template<
typename ReturnType, typename Args...,
ReturnType (*FuncPtr)(Args...)
>
wrapper(Args... args)
{
extra_processing();
return FuncPtr(args...);
}
...
wrapper<void, f>(); // calls f
wrapper<R, T, g>(T()); // calls g
wrapper<S, U, V, h>(U(), V()); // calls h
This works but is unsatisfactory because it is verbose. The return type and parameter types can be deduced from the function pointer itself. What would be perfect is a template specification so I can do wrapper<g>(T())
as indicated above.
Thanks for all help!