简体   繁体   English

使用mem_fun()作为智能指针的容器

[英]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. 我最近决定将指针向量更改为智能指针向量,但尽管这些智能指针与STL兼容,但我无法转换某些算法来使用它们。

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. 您可以假设my_smart_pointer <>与shared_ptr <>基本上具有相同的接口,但我不能在我的项目中使用boost。

Is there a (generic) adapter I could write to allow mem_fun or mem_fun_ref to work? 是否有一个(通用)适配器,我可以写,以允许mem_fun或mem_fun_ref工作? 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. 你想使用boost mem_fn,因为它完全符合你的要求。 Look at this link, specifically the PURPOSE section. 请看这个链接,特别是PURPOSE部分。

http://www.boost.org/doc/libs/1_45_0/libs/bind/mem_fn.html 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). 顺便说一下,你应该传递对const的引用,而不是is_any_valid中的整个向量(并且你的valid()也应该是const)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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