Search code examples
c++pointersstructfunction-pointers

C++ Calling pointer of a struct's function


I have a simple code as below:

int global1(int x)
{
 return x * 5;
}

int global2(int x)
{
 return x + 5;
}

struct some_struct {
  int a;

  int foo1(int x)
  {
     return x * a;
  }

  int foo2(int x)
  {
     return x + a;
  }

  int bar1(int x, bool a)
  {
     auto func = a ? global1 : global2; // works
     // auto func = a ? &global1 : &global2; // also works

     return func(x);
  }

  int problem_function(int x, bool a) // It is my question
  {
     auto func = a ? foo1 : foo2; // gives error
     // auto func = a ? &foo1 : &foo2; // also gives error
     // auto func = a ? &this->foo1 : &this->foo2; // also gives error

     return func(x);
  }
};

It is a very simplified form of the real code. I have no way to carry function on the outside like how I did in this with global1() & global2().

I want to call one of the functions in the struct, but using a pointer to a function, but it gives an error.

Note: I can't use if..else because in the real code it doesn't return func(x). In the real code, I use func(x) as a condition for a function in a loop (I am not joking, it's literaly what I said).

A part from the real code:

void* find_first(ExprToken* (*cond)(bool (*)(ExprToken*))) {...} // yeah

I know if I want to call a function of a struct, I have to tell the compiler which variable (struct) I am using, but how?

Does C++ even support a function pointer in a struct?

Sorry for the complexity, sometimes I forget what the real code is actually doing.


Solution

  • Resource: https://public.websites.umich.edu/~eecs381/handouts/Pointers_to_memberfuncs.pdf

    I found the answer on the internet and I wanted to share it under this question.

    Answer:

      int problem_function(int x, bool a) // It is my question
      {
         auto func = a ? &some_struct::foo1 : &some_struct::foo2;
    
         return (*this).*func(x);
      }