1. 程式人生 > >C++ 謂詞(predicate) 與 仿函式 ( functor (function object))

C++ 謂詞(predicate) 與 仿函式 ( functor (function object))

謂詞與函式物件

謂詞 predicate

C++ 標準定義謂詞如下:

The Predicate parameter is used whenever an algorithm expects a function object that when applied to the result of dereferencing the corresponding iterator returns a value testable as true. In other words, if an algorithm takes Predicate pred as its argument and first as its iterator argument, it should work correctly in the construct if (pred(*first)){...}. The function object pred shall not apply any non-constant function through the dereferenced iterator. This function object may be a pointer to function, or an object of a type with an appropriate function call operator.

換成中文就是:當一個演算法需要一函式物件,去應用於解引用(deferencing)迭代器(deferencing 解釋: int p;將定義一個指向整數的指標,並p取消引用該指標,這意味著它將實際檢索p指向的資料。)的結果,謂詞引數返回一個testable值為true。換句話說,換句話說, 如果演算法將預測 pred 作為其引數,第一個引數是迭代引數,則如果 (pred (* first)) {..} , 它應該在構造中正常工作。函式物件 pred 不應通過解引用迭代器應用於任何非定常(non-constant)函式。此函式物件可以是指向函式的指標, 也可以是具有適當函式呼叫運算子的型別的物件。

仿函式

functor(函式物件或函式)形式:object + ()