unary_function有一個兄弟是binary_function,倆格的區別是一個爲了使用一個參數輸入的函數對象,另外一個適合兩個輸入參數的函數對象。對於STL不熟悉的人,很難理解爲何好端端的函數對象, 爲嗎要從它們繼承呢?ios
其實這是由於STL適配器的須要,簡單說,若是僅僅是調用此函數對象的方法,那確實不用這些古怪的東西。不過若是您的函數對象須要靈活使用的時候,就會有問題了。咱們首先看一下下面程序。less
int main() { vector<int> vec(10, 1); int count1 = count_if(vec.begin(), vec.end(), bind2nd(less_equal<int>(), 10)); //求容器中小於等於10的元素個數 int count2 = count_if(vec.begin(), vec.end(), not1(bind2nd(less_equal<in t>(), 10))); //求容器中不小於等於10的元素個數,正好是上面函數的取反 cout<<count1<<' '<<count2<<endl; //10 0 return 0; }
一元運算符negate logical_not, 其餘邏輯運算符 less greater_equal等等,這些都是用模板的函數對象來實現的,因此要求函數對象都是來自同一個模板基類,才能匹配. 不然,在類型上,C++編譯器是沒法經過語義的, 而這些函數對象的原型也無法定義.ide
舉一個源碼例子:函數
//一元操做求反 template <class Predicate> class unary_negate: public unary_function<typename Predicate::argument_type, bool> { protected: Predicate pred; 6. public: explicit unary_negate(const Predicate& x) : pred(x) {} bool operator()(const typename Predicate::argument_type& x) const { return !pred(x); } };
若是沒有基類模板,這個函數子是無法子定義原型的.ui
An empty base struct that defines types that may be inherited by derived classes that provides a unary function object.
spa
template<class Arg, class Result> struct unary_function { typedef Arg argument_type; typedef Result result_type; };
The template struct serves as a base for classes that define a member function of the formresult_type operator()(const argument_type&) const.orm
All such derived unary functions can refer to their sole argument type as argument_type and their return type as result_type.對象
// functional_unary_function.cpp // compile with: /EHsc #include <vector> #include <functional> #include <algorithm> #include <iostream> using namespace std; // Creation of a user-defined function object // that inherits from the unary_function base class class greaterthan10: unary_function<int, bool> { public: result_type operator()(argument_type i) { return (result_type)(i > 10); } }; int main() { vector<int> v1; vector<int>::iterator Iter; int i; for (i = 0; i <= 5; i++) { v1.push_back(5 * i); } cout << "The vector v1 = ( " ; for (Iter = v1.begin(); Iter != v1.end(); Iter++) cout << *Iter << " "; cout << ")" << endl; vector<int>::iterator::difference_type result1; result1 = count_if(v1.begin(), v1.end(), greaterthan10()); cout << "The number of elements in v1 greater than 10 is: " << result1 << "." << endl; }
The vector v1 = ( 0 5 10 15 20 25 ) The number of elements in v1 greater than 10 is: 3.
Header: <functional>
Namespace: std