Home > Net >  How do I send the 'this' pointer to a function not by using 'instance.function()'
How do I send the 'this' pointer to a function not by using 'instance.function()'

Time:11-14

Can I send an instance to a function not by using the . operator?

For example:

// header file
class A 
{
public:
    void foo() {std::cout << "Hello" << std::endl;}
};
// main file
A instance = new A;
instance.foo();
// instead do something like this
A::foo(instance);

Can I do something like that?

CodePudding user response:

Yes, you can indirectly via std::invoke:

#include <functional>
#include <iostream>

struct A {
  void foo() {
    std::cerr << "hi\n";
  }
};

int main() {
  A a;
  std::invoke(&A::foo,a);
}

But std::invoke's implementation will internally probably just apply the .* operator.

CodePudding user response:

You're more than welcome to use the pointer to member syntax.

A instance;
auto fn = &A::foo;
(instance.*fn)();

.* is a different operator than .. Whether this is more readable is left as an exercise to the reader (hint: it's not)

  • Related