c++ std::bind

来源:互联网 发布:seo网络推广招聘 编辑:程序博客网 时间:2024/05/10 23:37

案例一:

#include "stdafx.h"#include <iostream>#include <functional>  using namespace std;void f(int n1, int n2, int n3){    cout << n1 << " " << n2 << " " << n3 << endl;}int main(){ // f的三个参数,全部绑定到值,对newFunc的调用将不需要提供参数    auto newFunc = std::bind(f, 2, 3, 4);    newFunc();    getchar();    return 1;}

打印结果:
这里写图片描述



#include "stdafx.h"#include <iostream>#include <functional>  using namespace std;using namespace std::placeholders;void f(int n1, int n2, int n3){    cout << n1 << " " << n2 << " " << n3 << endl;}int ret4(){    cout << "ret4() called" << endl;    return 4;}int main() {    // f参数都使用占位符绑定, 需要提供至少三个参数    auto mm = std::bind(f, _1, _2, _3);    mm(1, 2, 3);            // 1 2 3    mm(1, 2, 3, 4, 5);      // 1 2 3; 4和5被丢弃    mm(1, 2, 3, ret4());    // ret4() called<cr> 1 2 3; 会调用ret4(), 但是返回的4被丢弃    getchar();    return 1;}

打印结果如下:

这里写图片描述


FR:海涛高软(hunk Xu)

原创粉丝点击