std::bind 概述
std::bind
是 C++ 标准库中的一个函数适配器,位于 <functional>
头文件中。它允许你将一个可调用对象(如函数、成员函数、lambda 表达式等)与其参数绑定,生成一个新的可调用对象。
函数原型
std::bind
提供两种函数原型:
-
通用模板形式,不指定返回类型:
template< class F, class... Args > /* unspecified */ bind(F&& f, Args&&... args);
-
指定返回类型的形式:
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
对象以引用方式传递,避免不必要的拷贝。