mercredi 13 septembre 2023

Function invocation in `std::bind`

TLDR: How is std::bind actually works 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 is
  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 have done the job to distinguish an instance and a pointer, or I misunderstood something.

Sincere appreciations for any advice in advance.

Aucun commentaire:

Enregistrer un commentaire