当前位置: 首页 > news >正文

C++11中的std::bind的作用

std::bind 概述

std::bind 是 C++ 标准库中的一个函数适配器,位于 <functional> 头文件中。它允许你将一个可调用对象(如函数、成员函数、lambda 表达式等)与其参数绑定,生成一个新的可调用对象。

函数原型

std::bind 提供两种函数原型:

  1. 通用模板形式,不指定返回类型:

    template< class F, class... Args >
    /* unspecified */ bind(F&& f, Args&&... args);
    
  2. 指定返回类型的形式:

    template< class R, class F, class... Args >
    /* unspecified */ bind(F&& f, Args&&... args);
    

功能

std::bind 返回一个基于 f 的函数对象,其参数 args 可以是值、引用或占位符(如 _1_2, ..., _9)。

示例

1. 绑定普通函数

#include <iostream>
#include <functional>int add(int a, int b) { return a + b; }
auto adder = std::bind(add, std::placeholders::_1, 5);
std::cout << adder(10) << std::endl; // 输出 15

这里,add 是一个普通函数,我们使用占位符 _1 来表示第一个参数将在调用时提供,第二个参数被绑定为 5

2. 绑定成员函数

#include <iostream>
#include <functional>class Counter {
public:int count = 0;void increment(int amount) { count += amount; }
};int main() {Counter counter;auto incrementCounter = std::bind(&Counter::increment, &counter, std::placeholders::_1);incrementCounter(3); // counter.count 现在是 3incrementCounter(7); // counter.count 现在是 10std::cout << counter.count << std::endl; // 输出 10return 0;
}

这里,我们绑定了 Counter 类的成员函数 increment。注意,成员函数指针需要显式指定。

3. 绑定引用参数

默认情况下,std::bind 会拷贝非占位符参数到返回的可调用对象中。但是,有时我们希望以引用方式传递参数。

#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
#include <sstream>void appendText(std::ostringstream& os, const std::string& text) {os << text;
}int main() {std::vector<std::string> items = {"apple", "banana", "cherry"};std::ostringstream os;std::for_each(items.begin(), items.end(), std::bind(appendText, std::ref(os), std::placeholders::_1));std::cout << os.str() << std::endl; // 输出 "applebananacherry"return 0;
}

在这个例子中,我们使用 std::ref 来确保 ostringstream 对象以引用方式传递,避免不必要的拷贝。


http://www.mrgr.cn/news/23527.html

相关文章:

  • 【Qt】Qt界面美化 | 绘画
  • 【Linux:文件系统】
  • 02 三数排序
  • 枚举专题.
  • 钢铁百科:NM360D执行标准、NM360D焊接性能、NM360D应用范围
  • 第三天旅游线路预览——从禾木景区入口到景区换乘中心
  • 【云服务器介绍】选择指南 腾讯云 阿里云全配置对比 搭建web 个人开发 app 游戏服务器
  • SprinBoot+Vue高校就业管理系统设计与实现的设计与实现
  • Jmeter_循环获取请求接口的字段,并写入文件
  • 无人机动力系统设计之桨叶推力计算
  • 安装一些大模型微调相关的库
  • [苍穹外卖]-07使用缓存优化查询接口
  • 2024年PDF转换器大集合:哪4款是互联网人的首选?
  • TikTok内容电商:短视频与直播带货如何重塑消费者购物决策
  • 国产游戏蓄力,火山引擎ByteHouse助力游戏厂商造爆款
  • DFS算法专题(二)——穷举vs暴搜vs深搜vs回溯vs剪枝【OF决策树】
  • 骨传导耳机哪个牌子值得买?推荐五款表现出色的骨传导耳机!
  • 基于人工智能的个性化学习推荐系统
  • OpenCV结构分析与形状描述符(14)拟合直线函数fitLine()的使用
  • 【C#生态园】JSON数据处理利器盘点:六款C#库全方位对比