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.
There is an
operator()
defined forstd::function
that I've been using to replaceempty()
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With