Both forms are equivalent. I prefer the form which explicitly shows that the parameter is a pointer. The knowledge, that the parameter is a pointer is important, since you can pass the values NULL
, nullptr
or 0
as argument. Your program would compile, but crash if someone would do the function call f(0)
.
You always want to check if a function pointer is not a null pointer before calling the pointee, unless you are certain that it is not possible that your function is called with a NULL
, nullptr
or 0
argument.
If you use lambdas in your project, you should use `templates. Otherwise you can continue to use raw function pointers, but make sure that you check your function pointer (if necessary)
template <typename Function>
int f(const Function& functionp) {
if(functionp)
functionp();
return 20;
}
Lambdas and std::function<>
objects also have a bool
operator, so the line if(functionp)
will also work for those. It will evaluate to false
for std::function<>
objects which contain a nullptr and otherwise it will evaluate to true
for std::function<>
objects and lambdas.