TLDR:当使用类的实例或类的
std::bind
指针调用成员函数时,this
实际上是如何工作的?
注释:
this
在调用成员函数时隐式用作第一个参数std::placeholder
如何运作(instance.*ptr)()
这是代码:
#include <functional>
#include <iostream>
struct Test {
void test(const std::string &info) { std::cout << info << std::endl; }
};
int main() {
Test test;
// call with instance
std::bind(&Test::test, std::placeholders::_1, "call with instance")(test);
// call with `this`
std::bind(&Test::test, std::placeholders::_1,
"call with `this` pointer")(&test);
}
这段代码在我的平台上运行良好。所以我猜要么
std::bind
已经完成了区分实例和指针的工作,要么我误解了一些东西。
真诚感谢您提前提出的任何建议。
正如文档中提到的,当
f
的INVOKE(f, t1, t2, ..., tN)
是指向类T
的成员函数的指针时:
t1
是类 T
的实例或 T
的基类,它将相当于: (t1.*f)(t2, ..., tN)
t1
是 std::reference_wrapper
的特化,它将相当于: t1.get().*f
(*t1).*f
有关更多详细信息,请阅读文档。
我要感谢我的问题下面的所有评论,并且很羞于接受我自己的答案,因为我必须接受答案才能提出其他问题。如果有人能给出答案,我很乐意接受他