Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using mem_fun() for container of smart pointers

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.

like image 883
Grim Fandango Avatar asked Nov 22 '10 13:11

Grim Fandango


1 Answers

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).

like image 75
Jody Hagins Avatar answered Oct 01 '22 20:10

Jody Hagins