C++ 函数对象最佳实践
函数对象是什么
函数对象(Function Object),也称为仿函数(Functor),是C++中一种特殊的对象,它可以像函数一样被调用。本质上,函数对象是一个重载了函数调用运算符operator()
的类或结构体的实例。
提示
函数对象结合了面向对象编程和函数式编程的优点,是STL算法中非常重要的组成部分。
函数对象 vs 普通函数
// 普通函数
bool isGreater(int a, int b) {
return a > b;
}
// 函数对象
struct IsGreater {
bool operator()(int a, int b) const {
return a > b;
}
};
// 使用方式
int main() {
// 使用普通函数
bool result1 = isGreater(5, 3); // 调用函数
// 使用函数对象
IsGreater isGreaterObj;
bool result2 = isGreaterObj(5, 3); // 调用函数对象
return 0;
}
函数对象的优势
函数对象相比普通函数有以下几个主要优势:
- 可以保存状态 - 函数对象可以包含成员变量,从而在多次调用之间保存状态
- 可以作为模板参数 - STL算法广泛使用函数对象作为模板参数
- 内联效率更高 - 编译器更容易对函数对象进行内联优化
- 类型安全 - 编译时类型检查更严格
- 可以携带类型信息 - 通过typedef等方式提供类型信息
标准库中的函数对象
C++ STL在<functional>
头文件中定义了许多常用的函数对象:
算术函数对象
#include <functional>
#include <iostream>
int main() {
std::plus<int> add;
std::minus<int> subtract;
std::multiplies<int> multiply;
std::divides<int> divide;
std::modulus<int> modulo;
std::negate<int> negate;
std::cout << "加法: " << add(5, 3) << std::endl; // 输出: 8
std::cout << "减法: " << subtract(5, 3) << std::endl; // 输出: 2
std::cout << "乘法: " << multiply(5, 3) << std::endl; // 输出: 15
std::cout << "除法: " << divide(6, 3) << std::endl; // 输出: 2
std::cout << "取模: " << modulo(5, 3) << std::endl; // 输出: 2
std::cout << "取反: " << negate(5) << std::endl; // 输出: -5
return 0;
}