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 婆婆高寿祝福语大全简短