一、背景介绍: 函数指针始终不太灵活,它只能指向全局或静态函数,对于类成员函数、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
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有