How do I bind a conversion-to-bool operator using boost::bind or boost::lambda?
For example, suppose I have a class C, with an operator bool(), and a list<C>
. How do I use remove_if and bind/lambda to remov开发者_如何学Pythone all elements that, when converted to bool, evaluate to false?
You don't need to use std::bind
or std::remove_if
for this; std::remove
will suffice:
std::vector<T> v; // Assuming T provides some conversion to bool
// Remove all elements that evaluate to 'false':
v.erase(std::remove(v.begin(), v.end(), false), v.end());
Or, you can use the std::logical_not
function object with std::remove_if
:
v.erase(std::remove_if(v.begin(), v.end(), std::logical_not<T>()), v.end());
It is very rare that a class should implement an actual operator bool()
overload: due to problems with the C++ type system, providing such a conversion makes it very easy to mistakenly write incorrect code that makes use of the conversion where you don't expect it to be used. It is far better to implement the safe-bool idiom instead of an actual operator bool()
overload. The downside of this is that you can't actually bind to the operator bool()
overload since the safe-bool idiom relies on a conversion to some unspecified type.
use std::logical_not if you need to remove if the operator evaluates to false; if you need to remove if true, then you can use:
remove_if(..., ..., bind(&C::operator bool, _1));
精彩评论