c++c++11function-pointers

Function invocation in `std::bind`


TLDR: How does std::bind() actually work when calling a member function with an instance of a class or a this pointer of the class?

Notes:

  1. I know what a function adapter and a function object are.
  2. I know this is implicitly used as the first argument when calling a member function
  3. I know how std::placeholder works
  4. I know how to call a member function in a more ordinary way, like (instance.*ptr)()

Here is the code:

#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);
}

This code works fine on my platform. So, I guess, either std::bind() has done the job to distinguish an instance and a pointer, or I misunderstood something.


Solution

  • As this document mentions, when f of INVOKE(f, t1, t2, ..., tN) is a pointer to member function of class T:

    1. if t1 is an instance of class T or base class of T, it will be equivalent to: (t1.*f)(t2, ..., tN)
    2. if t1 is a specialization of std::reference_wrapper, it will be equivalent to: t1.get().*f
    3. otherwise, it will be (*t1).*f

    For more details, please read the doc.