You can pass a function using a function pointer:
template <class T> void anyT(T a, void(*F)(T)) { F(a); }
but then you cannot pass lambda:
auto printStr = [](std::string a) { cout << a << endl; }; anyT(foo, printStr);
An alternative approach would be to use std::function :
template <class T> void anyT(T a, std::function<void(T)> F) { F(a); }
or general template parameter:
template <class T, class F> void anyT(T a, F func) { func(t); }
This has the disadvantage that it cannot resolve overloaded functions, but you can use a helper function:
template<typename F> std::function<F> make_function(F *funPtr) { return std::function<F>(static_cast<F*>(funPtr)); }
and call anyT as follows:
string foo = "foo"; anyT(foo, make_function<void(std::string)>(&print));
source share