template<typename T>
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<val;} //call operator
};
Less_than<int> lti{42}; //lti(i) will compare i to 42 using <(i<42)
Less_than<string> 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<typename C,typename P>
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<int>& vec, const list<string>& lst, int x, const string& s)
{
cout << "number of values less than " << x << ": " <<count(vec,Less_than<int>{x}) << '\n';
cout << "number of values less than " << s << ": " <<count(lst,Less_than<string>{s}) << '\n';
}
Or is lambda expression:
void f(const Vector<int>& vec, const list<string>& lst, int x, const string& s)
{
cout << "number of values less than " << x << ": " << count(vec,[&](int a){return a<x;}) << '\n';
cout << "number of values less than " << s << ": " << count(lst,[&](const string& a){return a<s;}) << '\n';
}
About lambda expression:
template<class C, class Oper>
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<unique_ptr<Shape>> 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)
}