`std::bind`中的函数调用

问题描述 投票:0回答:1

TLDR:当使用类的实例或类的

std::bind
指针调用成员函数时,
this
实际上是如何工作的?

注释

  1. 我知道什么是函数适配器和函数对象了
  2. 我知道
    this
    在调用成员函数时隐式用作第一个参数
  3. 我知道
    std::placeholder
    如何运作
  4. 我知道如何以更普通的方式调用成员函数,例如
    (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
已经完成了区分实例和指针的工作,要么我误解了一些东西。

真诚感谢您提前提出的任何建议。

c++ c++11 function-pointers
1个回答
0
投票

正如文档中提到的,当

f
INVOKE(f, t1, t2, ..., tN)
是指向类
T
的成员函数的指针时:

  1. 如果
    t1
    是类
    T
    的实例或
    T
    的基类,它将相当于:
    (t1.*f)(t2, ..., tN)
  2. 如果
    t1
    std::reference_wrapper
    的特化,它将相当于:
    t1.get().*f
  3. 不然就
    (*t1).*f

有关更多详细信息,请阅读文档。

我要感谢我的问题下面的所有评论,并且很羞于接受我自己的答案,因为我必须接受答案才能提出其他问题。如果有人能给出答案,我很乐意接受他

© www.soinside.com 2019 - 2024. All rights reserved.