开发者

C++ How to have "NOT" (!) in Predicate?

开发者 https://www.devze.com 2023-01-22 23:20 出处:网络
It might be a stupid question but just wonder if there is any workaround. :) Is there any way to have \"Not\" in Predicate?

It might be a stupid question but just wonder if there is any workaround. :)

Is there any way to have "Not" in Predicate?

Example:

std::remove_if(s.begin(), s.end(), !IsCorrect); 
//                                 ^

Or, Do I have to create开发者_StackOverflow中文版 IsNotCorrect function anyways?


You can do it using std::not1, which negates a unary predicate:

#include <functional>

std::remove_if(s.begin(), s.end(), std::not1(std::ptr_fun(IsCorrect)));

If IsCorrect is an Adaptable Function then you don't need ptr_fun, but if it's just a plain function then you do.


Also you can try brutforce like this to any predicate in C++11

template<class Predicate>
class not {
    //Has it's inverse predicate
    Predicate _Pred;
public:

    //Construct with arguments
    //required to construct _Pred
    template<class... Args>
    not(Args&&... args);

    //bool operator() with
    //_Pred arguments
    template<class... Args>
    bool operator()(Args&&... args) const;
};

template<class Predicate>
template<class... Args>
not<Predicate>::not(Args&&... args): _Pred(args...) {}

template<class Predicate>
template<class... Args>
bool not<Predicate>::operator()
    (
    Args&&... args
    ) const { return !_Pred(args...); }
0

精彩评论

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