程序示例如下:
#include <functional>
#include <iostream>
using foo = void(int); // function pointer
void functional(foo f) {
f(1);
}
int foo2(int para) {
return para;
}
int foo3(int a, int b, int c) {
return 0;
}
int main() {
auto f = [](int value) {
std::cout << value << std::endl;
};
functional(f); // call by function pointer
f(1); // call by lambda expression
// std::function wraps a function that take int paremeter and returns int value
std::function<int(int)> func = foo2;
int important = 10;
std::function<int(int)> func2 = [&](int value) -> int {
return 1+value+important;
};
std::cout << func(10) << std::endl;
std::cout << func2(10) << std::endl;
// bind parameter 1, 2 on function foo, and use std::placeholders::_1 as placeholder
// for the first parameter.
auto bindFoo = std::bind(foo3, std::placeholders::_1, 1,2);
// when call bindFoo, we only need one param left
bindFoo(1);
return 0;
}
输出结果如下:

修改一些参数如下:
再看一下运行结果,是否与如下对应,是否理解这些。

这篇博客通过一个C++程序示例,展示了函数指针、lambda表达式和std::function的使用。程序中定义了不同类型的函数,包括普通函数、lambda和接受参数的成员函数。然后,使用函数指针调用函数,并通过std::function创建可调用对象。还演示了如何使用std::bind部分绑定函数参数。最后,展示了运行结果。
1056

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



