views:

220

answers:

2

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?

+3  A: 

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.

efotinis
Perfect, didn't think it'd be that easy, thanks!
gct
+1  A: 

A good special value could be a default-constructed boost::function.

An empty function evaluates false in a boolean context (like a NULL pointer), or you can use the empty() method to test if a function object wrapper actually contains a function. See the boost::function Tutorial.

Here is a code sample:

#include <boost/function.hpp>
#include <iostream>

typedef boost::function<void (int code)> t_err_callback;

void do_callback(int code)
{
    std::cout << "Error " << code << std::endl;
}

void my_func(int a, int b, t_err_callback err_callback=t_err_callback())
{
    bool error = true;   // An error happened
    int error_code = 15; // Error code
    if (error && !err_callback.empty())
        err_callback(error_code);
}

int main()
{
    my_func(0, 0);
    my_func(0, 0, do_callback);
}
Danilo Piazzalunga
I have to upvote this, because it's more or less the same code I used to test my answer. :)
efotinis