C++函数对象
2021-04-16
2 min read
C++函数对象
引言
在实际开发中我们常常希望函数定义与使用可以像变量一样方便,如:可以在一个函数作用域内临时定义,能够方便的当做函数参数进行传递等,而函数对象正是实现这类功能的理想方法;
概念:重载了 operator() 的类对象称为函数对象。当该对象调用 operator() 时,方式、效果同普通函数调用,故名函数对象,示例如下:
class Demo {
public:
// ...
void operator() (void) {
std::cout << "call operator() ()" << std::endl;
}
// ...
};
lambda与std::function
很多时候我们并不需要自己特地定义一个类并重载 operator() 这样复杂的操作,C++已经为我们提供了实现此功能的基础设施:lambda与std::function,以方便我们使用,示例代码如下:
#include <iostream>
#include <functional>
int main()
{
std::function<int(const int, const int)> sum = [](const int a, const int b) -> int {
return a + b;
};
auto dot = [](const int a, const int b) -> int { return a*b; };
int sumRes = sum(1, 2);
int dotRes = dot(1, 2);
std::cout << "sum = " << sumRes << std::endl;
std::cout << "dot = " << dotRes << std::endl;
std::vector<int> vec = {3, 1, 4};
std::for_each(vec.cbegin(), vec.cend(), [](const int n) -> void {
std::cout << "vec_i" << n << std::endl;
});
}
适用场景
lambda与std::function适用场景:
- 在函数中定义一个临时函数,就像定义一个变量一样方便;
- 将函数对象作为参数传入另一个函数中,省去了传入函数指针的繁琐操作;
版权声明:
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!