首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >std::function与std::bind

std::function与std::bind

作者头像
灰子学技术
发布2022-01-18 14:08:22
6680
发布2022-01-18 14:08:22
举报
文章被收录于专栏:灰子学技术灰子学技术

一、背景介绍: 函数指针始终不太灵活,它只能指向全局或静态函数,对于类成员函数、lambda表达式或其他可调用对象就无能为力了,因此,C++11推出了std::function与std::bind这两件大杀器,他们配合起来能够很好的替代函数指针。

二、内容介绍:

bind提供两类比较重要的功能:

一个是:可以自定义参数的位置,补充进来需要函数里面缺少的参数(备注:这里主要针对Class里面的成员函数里面的默认参数this)

1. 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 main()
{
    using namespace std::placeholders;  // for _1, _2, _3...
    std::cout << "1) argument reordering and pass-by-reference: ";
    int n = 7;
    // _1,_2,_3参数的顺序
    auto f1 = std::bind(f, _2, 42, _1, _3, n);
    n = 10;
    // 参数的对应关系为:1--》n3,2-->n1,42--->n2,1001-->n4,n-->n5
    f1(1, 2, 1001);  
    std::cout << "2) achieving the same effect using a lambda: ";
}

输出结果:
1) argument reordering and pass-by-reference: 2 42 1 1001 7
2) achieving the same effect using a lambda:

2.bind对Class的使用例子:

#include <random>
#include <iostream>
#include <memory>
#include <functional>
 
struct Foo {
    void print_sum(int n1, int n2)
{
        std::cout << n1+n2 << '\n';
    }
    int data = 10;
};
 
int main()
{
    using namespace std::placeholders;  // for _1, _2, _3...
    std::cout << "1) bind to a pointer to member function: ";
    Foo foo;
    // 这里的&foo就是为了补齐成员变量里面的默认参数this
    auto f3 = std::bind(&Foo::print_sum, &foo, 95, _1);
    f3(5);
    std::cout << "2) bind to a mem_fn that is a pointer to member function: ";
    
}
执行结果:
1) bind to a pointer to member function: 100
2) bind to a mem_fn that is a pointer to member function:

另一个是:可以使用std:ref和std:cref来使用引用。

#include <functional>
#include <iostream>
 
void f(int& n1, int& n2, const int& n3)
{
    std::cout << "In function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
    ++n1; // increments the copy of n1 stored in the function object
    ++n2; // increments the main()'s n2
    // ++n3; // compile error
}
 
int main()
{
    int n1 = 1, n2 = 2, n3 = 3;
    std::function<void()> bound_f = std::bind(f, n1, std::ref(n2), std::cref(n3));
    n1 = 10;
    n2 = 11;
    n3 = 12;
    std::cout << "Before function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
    bound_f();
    std::cout << "After function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
}
执行结果:
Before function: 10 11 12
In function: 1 11 12
After function: 10 12 12

https://en.cppreference.com/w/cpp/utility/functional/bind

https://cloud.tencent.com/developer/article/1474565

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2022-01-06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 灰子学技术 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档