class MyFunctor{public:int operator()(int x) { return x * 2;}}
MyFunctor doubler;int x = doubler(5);
真正的优点是仿函数可以保存状态。
class Matcher{int target;public:Matcher(int m) : target(m) {}bool operator()(int x) { return x == target;}}
Matcher Is5(5);
if (Is5(n)) // same as if (n == 5){ ....}
// this is a functorstruct add_x {add_x(int val) : x(val) {} // Constructorint operator()(int y) const { return x + y; }
private:int x;};
// Now you can use it like this:add_x add42(42); // create an instance of the functor classint i = add42(8); // and "call" itassert(i == 50); // and it added 42 to its argument
std::vector<int> in; // assume this contains a bunch of values)std::vector<int> out(in.size());// Pass a functor to std::transform, which calls the functor on every element// in the input sequence, and stores the result to the output sequencestd::transform(in.begin(), in.end(), out.begin(), add_x(1));assert(out[i] == in[i] + 1); // for all i
boost::function<void ()> f1 = boost::bind(foo, 2);f1();//no more argument, function argument stored in f1//and this print "Foo 2" (://and normal functionboost::function<void ()> b1 = boost::bind(&Bar, 2);b1();// print "Bar 2"
class SomeClass{std::string state_;public:SomeClass(const char* s) : state_(s) {}
void method( std::string param ){std::cout << state_ << param << std::endl;}};SomeClass *inst = new SomeClass("Hi, i am ");boost::function< void (std::string) > callback;callback = boost::bind(&SomeClass::method, inst, _1);//create delegate//_1 is a placeholder it holds plase for parametercallback("useless");//prints "Hi, i am useless"
class myFunctor{public:/* myFunctor is the constructor. parameterVar is the parameter passed tothe constructor. : is the initializer list operator. myObject is theprivate member object of the myFunctor class. parameterVar is passedto the () operator which takes it and adds it to myObject in theoverloaded () operator function. */myFunctor (int parameterVar) : myObject( parameterVar ) {}
/* the "operator" word is a keyword which indicates this function is anoverloaded operator function. The () following this just tells thecompiler that () is the operator being overloaded. Following that isthe parameter for the overloaded operator. This parameter is actuallythe argument "parameterVar" passed by the constructor we just wrote.The last part of this statement is the overloaded operators bodywhich adds the parameter passed to the member object. */int operator() (int myArgument) { return myObject + myArgument; }
private:int myObject; //Our private member object.};
// a template class for converting a member function of the type int function(int,int,int)//to be called as a function objecttemplate<typename _Ret,typename _Class,typename _arg1,typename _arg2,typename _arg3>class mem_fun3_t{public:explicit mem_fun3_t(_Ret (_Class::*_Pm)(_arg1,_arg2,_arg3)):m_Ptr(_Pm) //okay here we store the member function pointer for later use{}
//this operator call comes from the bind method_Ret operator()(_Class *_P, _arg1 arg1, _arg2 arg2, _arg3 arg3) const{return ((_P->*m_Ptr)(arg1,arg2,arg3));}private:_Ret (_Class::*m_Ptr)(_arg1,_arg2,_arg3);// method pointer signature};
template<typename _Func,typename _Ptr,typename _arg1,typename _arg2,typename _arg3>class binder3{public://This is the constructor that does the binding partbinder3(_Func fn,_Ptr ptr,_arg1 i,_arg2 j,_arg3 k):m_ptr(ptr),m_fn(fn),m1(i),m2(j),m3(k){}
//and this is the function objectvoid operator()() const{m_fn(m_ptr,m1,m2,m3);//that calls the operator}private:_Ptr m_ptr;_Func m_fn;_arg1 m1; _arg2 m2; _arg3 m3;};
typedef binder3<mem_fun3_t<int,T,int,int,int> ,T* ,int,int,int> F3;//and change the signature of the ctor//just to illustrate the usage with a method signature taking more than one parameterexplicit Command(T* pObj,F3* p_method,long timeout,const char* key,long priority = PRIO_NORMAL ):m_objptr(pObj),m_timeout(timeout),m_key(key),m_value(priority),method1(0),method0(0),method(0){method3 = p_method;}
#include <string>#include <vector>#include <algorithm>
template <typename T>T min3(const T& a, const T& b, const T& c){return std::min(std::min(a, b), c);}
class levenshtein_distance{mutable std::vector<std::vector<unsigned int> > matrix_;
public:explicit levenshtein_distance(size_t initial_size = 8): matrix_(initial_size, std::vector<unsigned int>(initial_size)){}
unsigned int operator()(const std::string& s, const std::string& t) const{const size_t m = s.size();const size_t n = t.size();// The distance between a string and the empty string is the string's lengthif (m == 0) {return n;}if (n == 0) {return m;}// Size the matrix as necessaryif (matrix_.size() < m + 1) {matrix_.resize(m + 1, matrix_[0]);}if (matrix_[0].size() < n + 1) {for (auto& mat : matrix_) {mat.resize(n + 1);}}// The top row and left column are prefixes that can be reached by// insertions and deletions aloneunsigned int i, j;for (i = 1; i <= m; ++i) {matrix_[i][0] = i;}for (j = 1; j <= n; ++j) {matrix_[0][j] = j;}// Fill in the rest of the matrixfor (j = 1; j <= n; ++j) {for (i = 1; i <= m; ++i) {unsigned int substitution_cost = s[i - 1] == t[j - 1] ? 0 : 1;matrix_[i][j] =min3(matrix_[i - 1][j] + 1, // Deletionmatrix_[i][j - 1] + 1, // Insertionmatrix_[i - 1][j - 1] + substitution_cost); // Substitution}}return matrix_[m][n];}};