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 现在是 3
    incrementCounter(7); // counter.count 现在是 10
    std::cout << counter.count << std::endl; // 输出 10
    return 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 对象以引用方式传递,避免不必要的拷贝。

  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值