Adding on the other answers, you can take advantage of the fact that:
The following code:
#include <type_traits>
template<class F>
struct A
{
A(F foo) : bar(foo) {}
typename std::conditional<std::is_function<F>::value,
typename std::add_pointer<F>::type,
F>::type bar;
};
is a generic solution allowing the same syntax for functions, function pointers, functors and lambdas:
#include <type_traits>
#include <iostream>
void Hello() { std::cout << "Function\n"; }
struct Hello2 { void operator()() { std::cout << "Struct\n"; } };
void Hello3() { std::cout << "Function pointer\n"; }
template<class F>
struct A
{
A(F foo) : bar(foo) { bar(); }
std::conditional_t<std::is_function<F>::value, std::add_pointer_t<F>, F> bar;
};
int main()
{
A<decltype(Hello)> a(Hello);
Hello2 h2;
A<decltype(h2)> b(h2);
A<decltype(&Hello3)> c(&Hello3);
auto Hello4 = []() { std::cout << "Lambda\n"; };
A<decltype(Hello4)> d(Hello4);
}
(here I've slightly changed the solution taking advantage of C++14 features).
Indeed std::function
is a (not always better) alternative.