I'm writing a C++ code with the Arduino framework. It uses the avr-gcc
compiler. I cannot use std::function
.
I set up a class with a callback and a simple example how I use it:
class GPI
{
public:
typedef void(*GpiCallback)(bool value);
GPI();
void Begin(byte pin, GpiCallback callback);
void Loop();
private:
GpiCallback _callback;
};
GPI::GPI() { }
void GPI::Begin(byte pin, GpiCallback callback)
{
// do something
_callback = callback;
}
void GPI::Loop()
{
// do something
_callback(value);
}
in another class:
class Engine
{
public:
Engine();
void Init();
// other members
private:
GPI _gpi;
bool _foo;
// other members
};
void Engine::Init()
{
_gpi.Begin(PIN_BUTTON, [](bool value)
{
Serial.print(F("[GPI] Button pressed"));
});
}
All this stuff works.
Now I want to access, inside the lambda function, to the other members of my Engine
class.
Reading the documentations about lambdas I thought it should be enough to capture the this
variable, i.e.:
_gpi.Begin(PIN_BUTTON, [this](bool value)
{
Serial.print(F("[GPI] Button pressed"));
_foo = true;
});
but I get a compiler error:
no conversion function exists from "lambda [](bool value)->void" to "GPI::GpiCallback"
I don't fully understand this message, actually. It reports the correct signature of the callback (even without the captured variable).
Why does capturing a variable lead to a wrong lambda signature?