0
我正在做測試以瞭解lambda表達式。我正試圖向用戶提供直接在主函數中重寫函數的功能。讓我解釋一下:建議用戶改寫lambda的功能
#include <iostream>
using namespace std;
class A {
public:
virtual bool execute() {};
};
class B : public A {
public:
bool execute() { cout << "Execute in B" << endl; }
};
int main() {
B newB;
newB.execute();
newB.execute() { cout << "Execute in New B" << endl; } ;
newB.execute();
return 0;
}
這個源代碼不起作用,因爲重寫這樣的函數是非法的。對於你來說,在C++ 14中重寫一個函數的最好方法是什麼?用lambda?沒有lambda?
我想要像Javascript一樣做,重載一個像這樣的函數:newB.somefunction = function(...){...} ;.我希望函數能夠被我的庫的用戶編寫在源代碼中。以某種方式回調函數。
我的問題如下:如何編寫回調函數或Lambda表達式來重寫類/對象外的方法?具有可變提出Exagon
解決方案:
#include <iostream>
#include <functional>
class B {
public:
int global=0;
std::function<void()> execute{
[](){
std::cout << "Hello World" << std::endl;
}
};
};
int main() {
B newB;
newB.execute();
newB.execute();
newB.execute = [newB](){std::cout << newB.global << " = FOOBAR\n";};
newB.execute();
return 0;
}
你想你的圖書館的用戶編寫源代碼的功能?還是你希望函數在應用程序的用戶運行時寫入? ...對於後者,請檢查[ChaiScript](http://chaiscript.com/) – WhiZTiM
你好ChaiScript,我想要像Javascript一樣做,重載一個這樣的函數:newB.somefunction = function(...){。 ..} ;.我希望函數能夠完全由我的庫的用戶在源代碼中編寫。 – AkrogAmes
聽起來像你想要某種形式的回調。改變你的類來接受一個'std :: function <>'int構造函數,並且當你調用execute時調用它。 – GManNickG