specify default value of std::function
void func(const std::function<void()>& f = {}) {
if(f) f();
}
LIVE DEMO
const std::function<void()>& f = nullptr
or
const std::function<void()>& f = std::function<void()>()
I would use a nullptr for the empty case. It can be used because you never use full function objects but only pointers to them, so func(f1);
will be in fact func(&f1)
=> you will always pass pointers to func, so nullptr
is IMHO the best candidate.
This compiles and run:
void func(const std::function<void()>& f = nullptr)
{
if(f)
f();
}
The alternative of using a default function would be:
void func(const std::function<void()>& f = std::function<void()>()) {
try {
f();
}
catch(std::bad_function_call e) {
}
}
using exception catching. The choice between the 2 mainly depends on whether you expect the empty case to occur; almost never: go with exception vs. sometimes: test before call.
As question mentions if (f)
, use nullptr
You can try like this:
const std::function<void()> & f = std::function<void()>()
As Basile added, the standard says:
§ 20.8.11.1 Class bad_function_call [func.wrap.badcall]
1/ An exception of type bad_function_call is thrown by function::operator() (20.8.11.2.4) when the function wrapper object has no target.