IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    C++ 泛型编程练习 Adaptor Functor & Helper Function

    abilitytao发表于 2014-09-29 15:50:00
    love 0
    #include
    using namespace std;

    template <class OutputIterator, class Iterator, class predicate>
    void copy(OutputIterator o, Iterator f, Iterator l, predicate p)
    {
    while(f!=l)
    {
    if(p(*f))
    {
    *o = *f;
    ++f;
    ++o;
    }
    else
    {
    ++f;
    }
    }

    }
    template <class Predicate>
    class negate
    {
    Predicate p;
    public :
    typedef typename Predicate::value_type value_type;
    negate(const Predicate &pred;):p(pred){}
    bool operator()(const value_type v)const
    {
    return !p(v);
    }
    };

    template<class Number>
    struct smallerThanX
    {
    typedef Number value_type;
    int x;
    smallerThanX(int x):x(x)
    {

    }

    bool operator()(const Number& n) const
    {
    return n< this->x;
    }
    };

    template <class Predicate>
    inline negate NOT (const Predicate &p;)
    {
    return negate
    (p);
    }


    int main()
    {
    int a[] = {1,2,3,4,5,6,7,8};
    int *b = new int [10];
    copy(b,a,a+8,NOT(smallerThanX<int>(5)));
    return 0;
    }

    这种方式实在是有点难看啊。。。 代码不仔细看还看不懂,不知道为什么要这样写呢。。。


    abilitytao 2014-09-29 23:50 发表评论


沪ICP备19023445号-2号
友情链接