C++的STL中binary_function是一个模板基类,主要用于规范二元函数对象的类型定义,让自定义的函数对象能够适配STL中各类算法的要求。它的核心作用是提供函数对象需要的参数类型和返回值类型别名,方便STL内部进行类型推导和适配。

binary_function 的基本定义
binary_function的模板定义非常简单,它位于<functional>头文件中,原型如下:
// binary_function 模板定义
template <class Arg1, class Arg2, class Result>
struct binary_function {
typedef Arg1 first_argument_type; // 第一个参数类型别名
typedef Arg2 second_argument_type; // 第二个参数类型别名
typedef Result result_type; // 返回值类型别名
};
这三个类型别名是binary_function的核心,很多STL的适配器比如bind2nd等,都需要函数对象提供这些类型别名才能正常工作。
如何使用 binary_function
使用binary_function的步骤很简单,只需要让自定义的二元函数对象公有继承它,并传入对应的参数类型和返回值类型即可。下面是一个计算两个数相加的函数对象示例:
#include <iostream>
#include <functional>
#include <algorithm>
#include <vector>
// 自定义加法函数对象,继承binary_function
struct Adder : public std::binary_function<int, int, int> {
int operator()(int a, int b) const {
return a + b;
}
};
int main() {
std::vector<int> nums = {1, 2, 3, 4, 5};
int base = 10;
// 使用bind2nd绑定第二个参数为base,这里需要函数对象有second_argument_type等别名
std::transform(nums.begin(), nums.end(), nums.begin(), std::bind2nd(Adder(), base));
for (int num : nums) {
std::cout << num << " ";
}
// 输出结果:11 12 13 14 15
return 0;
}
上面的代码中,Adder继承了binary_function<int, int, int>,因此自动拥有了first_argument_type、second_argument_type、result_type三个类型别名,这样std::bind2nd就能正确识别参数类型,完成参数绑定操作。
适用场景说明
binary_function主要适用于以下场景:
- 需要自定义二元函数对象,并且要让该函数对象适配STL中的函数适配器,比如bind2nd、ptr_fun等
- 希望函数对象符合STL的规范,让代码更具通用性,能够被更多STL算法兼容
- 需要明确函数对象的参数和返回值类型,方便其他开发者理解和使用该函数对象
现代C++中的替代方案
在C++11及之后的标准中,binary_function已经被标记为废弃,主要是因为新的标准引入了lambda表达式、std::function、std::bind等更灵活的特性,不再需要依赖binary_function来提供类型别名。上面的加法示例用lambda表达式可以这样实现:
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> nums = {1, 2, 3, 4, 5};
int base = 10;
// 使用lambda表达式替代自定义函数对象
std::transform(nums.begin(), nums.end(), nums.begin(), [base](int a) {
return a + base;
});
for (int num : nums) {
std::cout << num << " ";
}
return 0;
}
虽然binary_function已经不再被推荐使用,但理解它的用法对于阅读旧版本的C++代码、理解STL函数对象的设计逻辑仍然有很大帮助。
注意事项
- binary_function是结构体,默认成员都是公有的,继承时不需要额外声明访问权限
- 继承binary_function时,模板参数的顺序要和函数对象的参数顺序、返回值类型对应,第一个参数是operator()的第一个参数类型,第二个是第二个参数类型,第三个是返回值类型
- 自定义的函数对象的operator()最好声明为const成员函数,符合STL对函数对象的要求
binary_functionC++STL函数对象修改时间:2026-07-04 08:33:22