首页 > 代码库 > c++11: bind用法
c++11: bind用法
原型:
template< class R, class F, class... Args >
bind( F&& f, Args&&... args );
bind函数模板的作用是:
The function template bind
generates a forwarding call wrapper for f
. Calling this wrapper is equivalent to invoking f
with some of its arguments bound to args
.
不怎么好翻译,尝试解释一下:我们为某个函数做一个bind,然后调用该bind和调用函数是一样的,跟函数指针有点像。
#include <random>#include <iostream>#include <memory>#include <functional> void f(int n1, int n2, int n3, const int& n4, int n5){ std::cout << n1 << ‘ ‘ << n2 << ‘ ‘ << n3 << ‘ ‘ << n4 << ‘ ‘ << n5 << ‘\n‘;} int g(int n1){ return n1;} struct Foo { void print_sum(int n1, int n2) { std::cout << n1+n2 << ‘\n‘; } int data = http://www.mamicode.com/10;}; int main(){ using namespace std::placeholders; // for _1, _2, _3... // demonstrates argument reordering and pass-by-reference int n = 7; // (_1 and _2 are from std::placeholders, and represent future // arguments that will be passed to f1) auto f1 = std::bind(f, _2, _1, 42, std::cref(n), n); n = 10; f1(1, 2, 1001); // 1 is bound by _1, 2 is bound by _2, 1001 is unused // nested bind subexpressions share the placeholders auto f2 = std::bind(f, _3, std::bind(g, _3), _3, 4, 5); f2(10, 11, 12); // bind to a member function Foo foo; auto f3 = std::bind(&Foo::print_sum, &foo, 95, _1); f3(5); // bind to member data auto f4 = std::bind(&Foo::data, _1); std::cout << f4(foo) << ‘\n‘;
c++11: bind用法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。