Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value for boost::function argument?

I've got a function that I want to take an optional boost::function argument as a callback for reporting an error condition. Is there some special value I can use a the default value to make it optional?

For example, with a regular function pointer I can do:

void my_func(int a, int b, t_func_ptr err_callback=NULL) {

   if (error && (err_callback != NULL))
      err_callback();

}

Can I do something similar with boost::function replacing the function pointer?

like image 301
gct Avatar asked Feb 25 '10 21:02

gct


1 Answers

You can use 0 (C++'s equivalent of NULL) for the default value of a boost::function argument, which will result to an empty function object. You can test if it's empty by calling its empty() method, comparing it to 0, or simply using it in a boolean context:

void my_func(int a, int b, boost::function<void()> err_callback = 0) {
   if (error && err_callback)  // tests err_callback by converting to bool
      err_callback();
}

boost::function objects work pretty much like plain function pointers in this respect.

like image 146
efotinis Avatar answered Oct 30 '22 16:10

efotinis