本篇来介绍了C++中bind功能。
1 std::bind
在 C++ 里,std::bind 是一个函数模板,其作用是创建一个可调用对象,该对象可绑定到一组参数上。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 );
参数
F
:这是要绑定的可调用对象(像函数、函数指针、成员函数指针、函数对象等)的类型。Args
:这是要绑定的参数的类型包。f
:需要绑定的可调用对象。args
:要绑定到可调用对象上的参数。R
:可调用对象的返回类型(可选)。
返回值
std::bind
返回一个未指定类型的可调用对象,这个对象存储了f
和args
的副本或者引用,并且可以在后续被调用。
2 实例
2.1 基础的bind功能
被绑定的函数支持参数和返回值,参数通过std::placeholders::_1
的形式,注意这里_1
是特定的形式,表示第一个参数
//g++ test1.cpp -std=c++11 -o test1
#include <functional>
#include <string>
std::string myFunc(int a, float b)
{
char buf[256];
sprintf(buf, "receive a:%d, b:%.2f", a, b);
return std::string(buf);
}
int main()
{
auto bindFunc = std::bind(myFunc, std::placeholders::_1, std::placeholders: