C++ 使用 boost::function 实现 Functor 示例
下面是一个使用 boost::function 实现 Functor 的示例代码:
#include <iostream>
#include <boost/function.hpp>
class Functor : public boost::function<int(int)> {
public:
int operator()(int x) {
return x * x;
}
};
int main() {
Functor f;
std::cout << f(5) << std::endl; // 输出 25
return 0;
}
在这个示例中,我们定义了一个名为 Functor 的类,该类继承自 boost::function<int(int)>。我们重载了 operator() 函数,使得 Functor 对象可以像函数一样调用。
在 main 函数中,我们创建了一个 Functor 对象 f,并通过 f(5) 调用了 operator() 函数,输出了结果 25。
原文地址: https://www.cveoy.top/t/topic/lU7 著作权归作者所有。请勿转载和采集!