在《C++ Primer》中关于std::bind()的用法主要是调整函数的参数个数以及参数顺序, 本文展示了std::bind()如何绑定类的成员。根据cppreference的描述, std::bind()可绑定的对象有:
Callable object (function object, pointer to function, reference to function, pointer to member function, or pointer to data member) that will be bound to some arguments 可调用对象(包括函数对象, 函数指针, 函数引用, 类成员函数指针以及类成员数据)
其中函数对象, 函数指针, 函数引用我们平常见的比较多, 比较少见的是类成员函数指针以及类成员数据, 因为这两者并不是可调用对象。关于类成员函数的指针这篇博客涵盖了方方面面, 非常细致。举例如下:
struct Foo {
void f() {
cout << "Foo::f()" << endl;
}
function<void(void)> getf() {
return std::bind(&Foo::f, this);
}
int a = 4;
};
int main(int argc, char* argv[]){
//using std::placeholders::_1;
Foo foo;
//function<void(void)> f = std::bind(&Foo::f, &foo);
//f();
foo.getf()();
auto a = std::bind(&Foo::a, _1);//Foo::f()
cout << a(&foo) << endl;//4
return 0;
}
本文详细介绍了C++标准库中的std::bind()函数如何用于绑定类成员函数及成员变量,并通过具体示例展示了其使用方法。
1万+

被折叠的 条评论
为什么被折叠?



