C++ 具有lambda和std :: bind的std :: function
示例
#include <iostream>
#include <functional>
using std::placeholders::_1; //在std::bind示例中使用
int stdf_foobar (int x, std::function<int(int)> moo)
{
return x + moo(x); //std::functionmoo称为
}
int foo (int x) { return 2+x; }
int foo_2 (int x, int y) { return 9*x + y; }
int main()
{
int a = 2;
/* Function pointers */
std::cout << stdf_foobar(a, &foo) << std::endl; //6(2+(2+2))
//也可以是:stdf_foobar(2,foo)
/* Lambda expressions */
/* An unnamed closure from a lambda expression can be
* stored in a std::function object:
*/
int capture_value = 3;
std::cout << stdf_foobar(a,
[capture_value](int param) -> int { return 7 + capture_value * param; })
<< std::endl;
//结果:15==值+(7*capture_value*值)==2+(7+3*2)
/* std::bind expressions */
/* The result of a std::bind expression can be passed.
* For example by binding parameters to a function pointer call:
*/
int b = stdf_foobar(a, std::bind(foo_2, _1, 3));
std::cout << b << std::endl;
//b==23==2+(9*2+3)
int c = stdf_foobar(a, std::bind(foo_2, 5, _1));
std::cout << c << std::endl;
//c==49==2+(9*5+2)
return 0;
}
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语