'how to ( pascal : procedure of object ) in c++

I want to pass a class function as a parameter of C function in Pascal. It is achieved with the keyword (procedure of object) so the compiler will take care of 'this' parameter. But it seems complicated in c++.

#include <stdio.h>

typedef void (*func)(void);

class Class{
public:
    void sub(void)
    {
      printf("Foo");
    }
};

void test(func f)
{
  f();
}

int main()
{
 Class c;
 test(c.sub);
}
c++


Solution 1:[1]

You'll need the function to take a generic function type, either making it a template:

template <typename F>
void test(F f) {
    f();
}

or using type erasure:

#include <functional>

void test(std::function<void()> f) {
    f();
}

Then use either std::bind or a lambda to bind the member function to the object:

test(std::bind(&Class::sub, &c));
test([&]{c.sub();});

Solution 2:[2]

I have been searching for similar issue. There is an answer from someone zayats80888 (thank you).

    #include <functional>
        using TEventHandler = std::function<void(int)>;
        
        class Button
        {
          TEventHandler onClick;
          public:
            Button(){ onClick = NULL;};
            void Run() {
             if (onClick) onClick(42);
            };
        };
         
        class Page
        {
          Button Bnt1;
          void ClickHandler(int Arg){/*do smth by Btn1->onClick*/};
          Page() {
            Btn1 = new Button();
            Btn1->onClick = [this](int arg) { goToCountersPage(arg); };
          }
        }
    
    Page Page1;
    void main() {
     Page1 = new Page();
     //
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mike Seymour
Solution 2 Gerasim Gerasimov