How to negate a predicate function using operator ! in C++?

前端 未结 2 570
误落风尘
误落风尘 2020-12-19 14:52

I want to erase all the elements that do not satisfy a criterion. For example: delete all the characters in a string that are not digit. My solution using boost::is_digit wo

相关标签:
2条回答
  • 2020-12-19 15:34

    You should be able to use std::not1.

    std::unary_negate<my_is_digit> operator!( const my_is_digit& x )
    {
        return std::not1( x );
    }
    

    For this to work you have to #include <functional> and derive your my_is_digit functor from the utility class std::unary_function< char, bool >. This is purely a typedef helper and adds no runtime overhead to your functor.


    Complete working example:

    #include <string>
    #include <algorithm>
    #include <functional>
    #include <iostream>
    #include <ostream>
    
    struct my_is_digit : std::unary_function<char, bool>
    {
        bool operator()(char c) const
        {
            return c >= '0' && c <= '9';
        }
    };
    
    std::unary_negate<my_is_digit> operator!( const my_is_digit& x )
    {
        return std::not1( x );
    }
    
    int main() {
        std::string s( "1a2b3c4d" );
        s.erase( std::remove_if( s.begin(), s.end(), !my_is_digit() ), s.end() );
        std::cout << s << std::endl;
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-19 15:43

    How could I implement such a ! like boost::is_digit()

    ...presumably you could look at the code that forms the is_digit implementation? You will see predicate_facade and the relevant code:

    template<typename PredT>
    inline detail::pred_notF<PredT>
    operator!( const predicate_facade<PredT>& Pred )
    {
    // Doing the static_cast with the pointer instead of the reference
    // is a workaround for some compilers which have problems with
    // static_cast's of template references, i.e. CW8. /grafik/
    return detail::pred_notF<PredT>(*static_cast<const PredT*>(&Pred)); 
    }
    
    0 讨论(0)
提交回复
热议问题