开发者

accessing static members using boost lambda

I am trying to write some simple predicate using boost::lambda and I am getting tons of errors.

I checked the documentation and I have some doubt on accessing the static variable std::string::npos in a lambda expression. Below my code.

    #include <boost/lambda/lambda.hpp>
    #include <boost/lambda/core.hpp>
    #include <boost/lambda/bind.hpp>

int main( int argc, char** argv ){
        typedef std::vector< std::string > array;
        namespace bl = boost::lambda;

        size_t ( std::string::* fp )( const std::string&, size_t ) const  
                  = &std::string::find;

        std::string to_find( "AA" );
        size_t pos = 0;

        const char* data [] = { "AAAA","BBBB","","CCAACC","DDDDD" };
        array v( data, data +4 );
        assert( v.size() == 4 );
        std::replace_if(
                v.begin()
                ,v.end()
                , bl::bind( 
                             fp
                             , bl::_1
                             , bl::constant_ref( to_find ) 
           开发者_开发问答                  , bl::var( pos ) 
                     ) != bl::bind( &std::string::npos, bl::_1 )
                , "||"
        );  
        return 0;
}

If I change the comparison

        != bl::bind( &std::string::npos, bl::_1 )
        to 
        != std::string::npos

it builds fine, but I am not sure if the expression is well formed. Sometimes I found that, because of lazy evaluation in lambda, I didn't get the expected result ( not in this case but in previous test with lambda ) because the call might be delayed.

Do you know in general what would be the right way to access a static member in boost lambda?

I thank you all

AFG


Accessing a static variable can be done using simply one of the following

 boost::constant( std::string::npos )
 boost::var( std::string::npos )

Depending on the input parameter signature also boost::constant_ref.


std::string::npos is a static member. It doesn't vary based on which string instance you're using. Your change to use != std::string::npos is correct.

Using boost::constant or boost::var allows you to delay evaluation of the static member's value. Without any modifiers, its value will be evaluated once, at the time the replace_if parameters are evaluated (the same time as v.begin() and v.end()). If you need to delay evaluation until the point where the bound expression is executed (inside of replace_if), then use boost::constant or boost::var, and if the static member's value changes over the course of the function, those changes will be visible inside the bound expression.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜