C# has generic function types such as Action<T> or Func<T,U,V,...>
With the advent of C++0x and the ability to have template typedef’s and variadic template parameters, it seems this should be possible.
The obvious solution to me would be this:
template <typename T>
using Action<T> = void (*)(T);
however, this does not accommodate for functors or C++0x lambdas, and beyond that, does not compile with the error “expected unqualified-id before 'using'“
My next attempt was to perhaps use boost::function:
template <typename T>
using Action<T> = boost::function<void (T)>;
This doesn’t compile either, for the same reason.
My only other idea would be STL style template arguments:
template <typename T, typename Action>
void foo(T value, Action f) {
f(value);
}
But this doesn’t provide a strongly typed solution, and is only relevant inside the templated function.
Now, I will be the first to admit that I am not the C++ wiz I prefer to think I am, so it’s very possible there is an obvious solution I’m not seeing.
Is it possible to have C# style generic function types in C++?
I think the syntax should be like this:
I couldn’t get that to compile either, though (g++ v4.3.2).
The general STL style function template is not strongly typed in the strictest sense, but it is type safe in the sense that the compiler will ensure that the template is only instantiated for types that fulfill all the requirements of the function. Specifically it will be a compiler error if the
Actionis not callable with one parameter of typeT. This a very flexible approach since it doesn’t matter ifActionis instantiated to be a function or some class that implementsoperator().The old non-C++0x workaround for the missing templated typedef would be to use a templated struct with a nested typedef: