I have recently taken the decision of changing a vector of pointers into a vector of smart pointers, but although these smart pointers are STL-compatible, I could not convert some algorithms to use them.
Consider a
class Base
{
...
virtual bool valid();
};
How do you convert
bool is_any_valid( vector< Base* > v )
{
return v.end() !=
find_if( v.begin(), v.end(), mem_fun( &Base::valid ) );
}
into this ?
bool is_any_valid( vector< my_smart_ptr< Base > v )
{
// mem_fun() fails, because valid() is not a member of my_smart_ptr< Base > !!!
// return v.end() !=
// find_if( v.begin(), v.end(), mem_fun( &Base::valid ) );
}
You can assume that my_smart_pointer<> has essentially the same interface as shared_ptr<>, but I can't use boost in my project.
Is there a (generic) adapter I could write to allow mem_fun or mem_fun_ref to work? I preferably look for an in-line solution, like:
find_if( v.begin(), v.end(), mem_fun( some_adapter( &Base::valid ) ) );
because there are many similar occurrences of such lines.
You want to use boost mem_fn, as it does exactly what you want. Look at this link, specifically the PURPOSE section.
http://www.boost.org/doc/libs/1_45_0/libs/bind/mem_fn.html
BTW, you should be passing a reference to const, and not the entire vector in is_any_valid (and your valid() should be const as well).
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