天天看點

C++ 仿函數是幹什麼用的

問題

C++ 仿函數是幹什麼用的?

回答

仿函數,其實就是重載了括号運算符 () 的對象, 不過它具有函數的一些性質, 可以在需要函數的地方(主要是各種容器和算法)使用。

struct add_x {
  add_x(int val) : x(val) {}  // Constructor
  int 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 class
int i = add42(8); // and "call" it
assert(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());
std::transform(in.begin(), in.end(), out.begin(), add_x(1)); 
assert(out[i] == in[i] + 1); // for all i           

複制

跟普通函數最大的不同是:仿函數可以擁有(多個)狀态。就像上面的

add42

,通過構造函數裡的參數傳入值。這樣我們在需要時,就可以再構造一個

add1

add2

來使用,更靈活。如果換成普通函數,那麼就需要多傳入一個參數。

C++11 帶來了

std::bind

std::function

,它們也可以完成仿函數的工作。