C++ 函数对象与 Lambda 表达式探索
1. 函数对象(Functors)
函数对象,也称为仿函数,是一种可以像函数一样被调用的对象。与普通函数不同的是,函数对象可以在不同的调用之间保持状态。下面是一个使用函数对象计算向量中浮点数平均值的示例:
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <source_location>
struct Mean {
Mean() = default;
void operator()(const double& val) {
std::cout << std::source_location::current()
.function_name() << " of " << this << '\n';
sum += val;
++count;
}
private:
double sum{};
int count{};
friend std::ostream& operator<<(std::ostream& os, const
Mean& a);
};
std::ostream& operator<<(std::ostream& os, cons
超级会员免费看
订阅专栏 解锁全文
712

被折叠的 条评论
为什么被折叠?



