要将书写函数对象的进程简单化, 标准库提供两个类模板作为这样的对象的基类: std::unary_function 和 std::binary_function.
它们都在头文件 < functional > 中声明.
unary_function:
根据其命名, unary_function 提供接收一个参数的基函数而 binary_function 提供一个接收两个参数的基函数.
定义类型能由派生类继承提供一元求函数对象的空的基本结构。
template<class Arg, class Result> struct unary_function { typedef Arg argument_type; typedef Result 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; }
<span id="mt4" class="sentence" data-guid="b44318f795d162c9e90b8f41bc887435" data-source="" the="" vector="" v1="(" 0="" 5="" 10="" 15="" 20="" 25="" )"="" xml:space="preserve"> 这个矢量v1 = (0 5 10 15 20 25)元素数大于v1的大于10是:3.
binary_function:
说明如何在 Visual C++ 中使用 (STL)标准模板库 (stl) 中 binary_function 结构。
template<class _A1, class _A2, class _R> struct binary_function { typedef _A1 first_argument_type; typedef _A2 second_argument_type; typedef _R result_type; };
// binfunc.cpp // compile with: /EHsc // // Structure used: binary_function<A,B,C> - base // class used to create operator // functions taking data types A // and B and returning data type C. #include <functional> #include <iostream> using namespace std ; class binary_test : public binary_function<binary_test &,int,float> { public: float value; binary_test(){value=10.0;} binary_test(float x){value=x;} result_type operator<<(second_argument_type arg2); }; binary_test::result_type binary_test::operator<<(binary_test::second_argument_type arg2) { value = (float)(((int)value) << arg2); cout << "New value after shift is " << value << endl; return value; } int main(void) { binary_test item; cout << "Begin" << endl; item = item << 2; }