0

I have this code in c++11

// To register a callback
void registerCallback(void (*fnPtr)(int state)) {
}

class Test {
public:
    // To pass in the callback
    void helloTest(int state) {   
    }

    void registerTheCallbackHere()
    {
        // This does not pass ( I want to it to pass)
        auto lamda = [this](int state) {
            this->helloTest(state);
        };
        registerCallback(lamda); // error here

        // But this one pass 
        auto lamda2 = [](int state) {
        };
        registerCallback(lamda2); // no error
    }
};

I have a function that a callback function as argument called registerCallback. I have class Test which has a method "helloTest". I want to pass this method to the register call back inside another method of Test class called registerTheCallbackHere using a lamda function but it's not working. Note: the registerCallback can't be modified. It is implemented in a library. Can you help please with an alternative solution.

1 Answers1

0

Only the captureless lambda can bind to your registerCallback function's parameter, but if you can modify your registerCallback function then you can use std::function:

#include <functional>

void registerCallback(std::function<void(int)> fnPtr) { }

(I passed it by value but you may decide to pass it by reference.)

Possible future problems:

  • You can't pass a move-only lambda to std::function therefore you can't have a captured unique_ptr in your lambda captures.
    • solution 1: shared_ptr
    • solution 2: c++23 std::move_only_function
  • lambdas are immutable by default (and that's what you should prefer)
    • you may have to declare your lambda mutable if you want to change its state (the state of the captured members)
pdani
  • 1
  • 1