1. 从回调机制看std::function的价值
在C++中处理回调函数时,开发者通常面临一个核心矛盾:既需要统一的调用接口,又要保留不同可调用对象的特性。传统C风格的函数指针虽然高效,但无法捕获上下文状态;而面向对象的虚函数机制又引入了额外的运行时开销。这正是std::function的设计初衷——提供一种类型安全的通用函数包装器。
我曾在音视频处理框架的开发中深刻体会到这种需求。当需要实现一个支持多种滤波算法的模块时,每个算法可能有不同的参数配置和内部状态。使用std::function作为回调接口,既允许算法以lambda形式携带私有状态,又能保持统一的调用签名。例如:
cpp复制using FilterCallback = std::function<void(uint8_t* frame, int width, int height)>;
class VideoPipeline {
public:
void addFilter(FilterCallback filter) {
filters_.push_back(filter);
}
void processFrame(uint8_t* frame) {
for (auto& filter : filters_) {
filter(frame, width_, height_);
}
}
private:
std::vector<FilterCallback> filters_;
int width_, height_;
};
这种设计模式下,调用者可以自由选择函数实现方式:
cpp复制// 普通函数
void GaussianBlur(uint8_t* frame, int w, int h) { /*...*/ }
// 带状态的lambda
auto sharpeningFilter = [kernel=createSharpenKernel()](uint8_t* frame, int w, int h) {
applyKernel(frame, w, h, kernel);
};
VideoPipeline pipel
