欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

玩转C++ STL标准库:理解仿函数和函数对象 - 第四部分:二元函数对象 binary_function

最编程 2024-01-12 18:18:24
...

二元函数对象,该结构体(类)的 operator()成员函数采用 二个参数

binary_function只是一个基类模板,它只定义了两个参数和返回值的类型,本身并不重载 operator(),这个任务应该交由派生类去实现。

template <class Arg1, class Arg2, class Result>
 struct binary_function {
   typedef Arg1 first_argument_type;
   typedef Arg2 second_argument_type;
   typedef Result result_type;
 };

代码示例:

#include<iostream>

#include<functional>
using  namespace  std;

二元函数对象,求最小值
//struct  Min
//{
//	int  operator()(const  int & a, const int & b) //因为有两个参数
//	{
//		return  a < b ? a : b;
//	} 
//};

//二元函数对象,求最小值
struct  Min: public   binary_function<const int &,const int&,int>
{
   result_type  operator()(first_argument_type  a, second_argument_type  b) //因为有两个参数
   {
   	return  a < b ? a : b;
   }
};


int main()
{
   //cout << "求最小值:" << Min()(111,222) << endl;
   Min::first_argument_type  a2 = 111;
   Min::second_argument_type  b2 = 222;
   Min::result_type  c2 = Min()(a2, b2);
   cout << "求最小值:" << c2<< endl;

   return 0;
}