我想将在“ CbSetter”类构造函数中定义的回调传递给“ CbReceptor”类构造函数,以将其设置为类成员。如果我不使用lambda上下文也可以。但是,如果设置了上下文,它将发出错误:
/home/user/Arduino/sketch_jan06b/sketch_jan06b.ino: In constructor 'CbSetter::CbSetter()':
sketch_jan06b:28:8: error: no matching function for call to 'CbReceptor::CbReceptor(CbSetter::CbSetter()::<lambda()>)'
});
^
/home/user/Arduino/sketch_jan06b/sketch_jan06b.ino:9:5: note: candidate: CbReceptor::CbReceptor(Callback)
CbReceptor(Callback callback)
^
/home/user/Arduino/sketch_jan06b/sketch_jan06b.ino:9:5: note: no known conversion for argument 1 from 'CbSetter::CbSetter()::<lambda()>' to 'Callback {aka void (*)()}'
/home/user/Arduino/sketch_jan06b/sketch_jan06b.ino:4:7: note: candidate: constexpr CbReceptor::CbReceptor(const CbReceptor&)
class CbReceptor
^
/home/user/Arduino/sketch_jan06b/sketch_jan06b.ino:4:7: note: no known conversion for argument 1 from 'CbSetter::CbSetter()::<lambda()>' to 'const CbReceptor&'
/home/user/Arduino/sketch_jan06b/sketch_jan06b.ino:4:7: note: candidate: constexpr CbReceptor::CbReceptor(CbReceptor&&)
/home/user/Arduino/sketch_jan06b/sketch_jan06b.ino:4:7: note: no known conversion for argument 1 from 'CbSetter::CbSetter()::<lambda()>' to 'CbReceptor&&'
exit status 1
no matching function for call to 'CbReceptor::CbReceptor(CbSetter::CbSetter()::<lambda()>)'
代码是:
typedef void (*Callback)();
class CbReceptor
{
Callback cb;
public:
CbReceptor(Callback callback)
{
cb = callback;
cb();
}
};
class CbSetter
{
public:
CbSetter()
{
// Doesn't emit an error but dosn't have a context
//Callback cb = [] () {};
// emits error
Callback cb = [=] () { contextMethod(); };
CbReceptor* receptor = new CbReceptor(cb);
}
private:
void contextMethod()
{
Serial.println("I've called!");
}
};
void setup() {
Serial.begin(9600);
CbSetter* setter = new CbSetter();
}
void loop() {
}
也许我在想错方法。我很喜欢TypeScript,在JS中传递回调是很平常的事情,但是不幸的是,在C ++中却没有。也许还有其他方法可以将回调从另一个类传递到一个类。
在Arduino Web编辑器和Linux上本地安装的编辑器中,结果相同。
此问题与passing-capturing-lambda-as-function-pointer不同,因为真正的问题是将类方法作为上下文传递。在那个问题中,上下文只是静态函数中的一个变量。