Search code examples
c++functionpolymorphismmember

lambda expression to assign a member function pointer


I need the syntax for a lambda expression that will return a pointer to a member function.

For example I have class A:

class A
{
int x;
void (A::*SomeFunction)();
}

I want to set SomeFunction to a lambda. I tried doing it like this:

A a();
a.SomeFunction = [this](){ printf("Hello from lambada %d",this->x);};

The problem is that:

[this](){ printf("Hello from lambda %d",this->x);};

does not give me a pointer to a member function of class A. it gives me a pointer to a normal function. How do i declare inside the lambda that this is a member function of A.

Alternativly if such a thing isn't possible in cpp. How do you suggest I'll access variable x of class A from the function that SomeFunction is pointing at without using virtual functions (this kind of code will run about 700 times per second).

Edit:

To make it clear I do care about performance. but the main reason why I need this is specific design problems not performance. I understand this is probably not possible to do in cpp. Workarounds suggestions would be welcomed.


Solution

  • From the comments:

    This is part of an ECS implemention. and I am simply not willing to create a new class for etch system i want to give the user the option to declare the system in the scene constructor or inheriate from the system class.

    You want different behavior from the same class without any indirection? You'll have to give up one.

    But you don't have to write a class for each system either. You can make the class a template, so the compiler can generate a class for each systems:

    template<typename T>
    struct A : private T {
        A(T function) noexcept : T{std::move(function)} {}
    
        void SomeFunction() {
            (*this)(this);
        }
    
        int x = 0;
    };
    

    It can then be used like that:

    auto lambda = [](auto a){ printf("Hello from lambda %d",a->x); };
    auto my_a = A{lambda}; // Generate a new A type from lambda
    
    my_a.SomeFunction(); // calls the lambda!