简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM