Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting boost::function to std::function

I'm updating some of our old code to use C++11 features in place of boost equivalents. However not everything is a simple namespace replacement like unordered containers and smart pointers.

For example boost::function has methods empty() and clear() but std::function does not.

There is an operator() defined for std::function that I've been using to replace empty() references but what should I use to replace clear() references?

I've considered using the std::function assignment operator and assigning nullptr to clear it but I'm worried that might have unintentional side affects of clearing not only the underlying function but rendering the object unusable.

Obviously, the better solution would be default initialization of any reusable member function objects that way there is always a valid callback which can simply be updated with a user provided one but I'm just aiming for a direct replacement of the previous usage right now not a code review.

like image 296
AJG85 Avatar asked Jun 22 '12 18:06

AJG85


1 Answers

There is an operator() defined for std::function that I've been using to replace empty()

Do you mean an operator! ?

For empty use that operator to test it in a boolean context:

if (f.empty())

becomes:

if (!f)

Or

if (!f.empty())

becomes:

if (f)

(That also works with boost::function, which also has operator! and operator bool.)

For clear assign nullptr to it, which doesn't render it unusable, it just sets it to a default-constructed state:

f.clear();

becomes

f = nullptr;

Or (thanks to Paul Groke for the suggestion):

f = {};

That's equivalent to:

f = decltype(f){};

but is more efficient, and much easier to type and easier to read!

like image 100
Jonathan Wakely Avatar answered Sep 21 '22 13:09

Jonathan Wakely