函数对象--Function Objects

template

class Less_than{

    const T val;                 //val to compare against

public:

    Less_than(const T& v):val(v){}

    bool operator()(const T& x) const {return x lti{42};           //lti(i) will compare i to 42 using <(i<42)

Less_than lts{"Backus"};   //lts(s) will compare s to "Backus" using <(s<"Backus")

void fct(int n,const string& s)

{

    bool b1=lti(n);                  //true if n<42;

    bool b2=lts(s);                  //true if s<"Backus"

    //...

}

template

int count(const C& c, P pred)

{

    int cnt=0;

    for(const auto& x : c)

        if(pred(x))

            ++cnt;

    return cnt;

}

void f(const Vector& vec, const list& lst, int x, const string& s)

{

    cout << "number of values less than " << x << ": " <{x}) << '\n';

    cout << "number of values less than " << s << ": " <{s}) << '\n';

}

或者是用lambda expression:

void f(const Vector& vec, const list& lst, int x, const string& s)

{

    cout << "number of values less than " << x << ": " << count(vec,[&](int a){return a

void for_all(C& c, Oper op)                              //assume that C is a container of pointers

{

    for(auto& x : c)

        op(*x);                                                 //pass op() a reference to each element pointed to

}

void user()

{  

    vector> v;

    while(cin)

        v.push_back(read_shape(cin));

    for_all(v,[](Shape& s){s.draw();});                   //draw_all()

    for_all(v,[](Shape& s){s.rotate(45);});              //rotate_all(45)

}

  

你可能感兴趣的:(函数对象--Function Objects)