Combining Predicates

后端 未结 3 1526
夕颜
夕颜 2021-01-05 09:08

Is there any way that you can combine predicates?

Lets say I have something like this:

class MatchBeginning : public binary_function

        
3条回答
  •  借酒劲吻你
    2021-01-05 09:26

    If you want to compose predicates, the nicest way to write it is probably using the Boost Lambda or Boost Phoenix:

    // Lambda way:
    // Needs:
    // #include 
    // #include 
    {
        using namespace boost::lambda;
        foo_vec::const_iterator it
            = std::find_if(
                        tokens.begin(),
                        tokens.end(),
                        bind(MatchBeginning(), _1, "-b") || !bind(MatchBeginning(), _1, "-")
                        );
    }
    // Boost bind way:
    // Needs:
    // #include 
    {
        foo_vec::const_iterator it
            = std::find_if(
                        tokens.begin(),
                        tokens.end(),
                        boost::bind(
                                    std::logical_or(),
                                    boost::bind(MatchBeginning(), _1, "-b"),
                                    !boost::bind(MatchBeginning(), _1, "-") // ! overloaded in bind
                                   )
                        );
    

    For the Phoenix way one of the possibilities is to use phoenix lazy functions, and the solution could look similar to the one below:

    // Requires:
    // #include 
    // #include 
    // #include 
    namespace phx = boost::phoenix;
    
    struct match_beginning_impl
    {
        template 
        struct result
        {
            typedef bool type;
        };
    
        template 
        bool operator()(Arg1 arg1, Arg2 arg2) const
        {
            // Do stuff
        }
    };
    phx::function match_beginning;
    
    using phx::arg_names::arg1;
    
    foo_vec::const_iterator it
        = std::find_if(
                    tokens.begin(),
                    tokens.end(),
                    match_beginning(arg1, "-b") || !match_beginning(arg1, "-")
                    );
    

    However to accomplish your task it probably makes more sense to employ different tools - for example: regular expressions (Boost Regex or Boost Xpressive). If you want to handle the command line options then use Boost Program Options.

提交回复
热议问题