C++编程中,有些时候需要传入函数作为参数,这在STL中作为谓词经常用到。传入的可以是函数、函数对象和lambda表达式。编程的时候,把它当成一个模板类型传入即可。以下给出一个简单的例子:
#include <iostream>
#include <utility>
#include <functional>
template<typename F>
void foo(F f) {
auto&& res = f();
std::cout << res << std::endl;
}
int f1(int n) {
return 2 * n;
}
bool f2() {
return 0.1;
}
struct Obj {
int operator()(int a, int b) {
return a + b;
}
};
int main() {
foo(std::bind(&f1, 10)); // 一元参数
foo(std::bind(&f2)); // 无参数函数
int x = 10;
foo([&]() { return x; }); // lambda表达式
Obj obj;
foo(std::bind(obj, 1, 2)); // 函数对象
return 0;
}