2017-01-29 43 views
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; 
} 
+0

你想你的圖書館的用戶編寫源代碼的功能?還是你希望函數在應用程序的用戶運行時寫入? ...對於後者,請檢查[ChaiScript](http://chaiscript.com/) – WhiZTiM

+1

你好ChaiScript,我想要像Javascript一樣做,重載一個這樣的函數:newB.somefunction = function(...){。 ..} ;.我希望函數能夠完全由我的庫的用戶在源代碼中編寫。 – AkrogAmes

+0

聽起來像你想要某種形式的回調。改變你的類來接受一個'std :: function <>'int構造函數,並且當你調用execute時調用它。 – GManNickG

回答

1

您可以從functional頭做到這一點使用std::function。 然後創建一個std::function成員併爲此成員創建一個setter。 execute成員函數需要調用這個std::function成員。 您可以將lambda傳遞給setter方法。 這裏是我的方法:

#include <iostream> 
#include <functional> 

class B { 
public: 
    void execute() {_f();} 
    void setFunction(std::function<void()> f){ _f = f;} 
private: 
    std::function<void()> _f{[](){std::cout << "Hello World" << std::endl;}}; 
}; 

int main() { 

    B newB; 
    newB.execute(); 
    newB.execute(); 

    newB.setFunction([](){std::cout << "FOOBAR\n";}); 

    newB.execute(); 
    return 0; 
} 

輸出爲:

Hello World 
Hello World 
FOOBAR 

既然你以後有事 「的JavaScript樣」,你可以做這樣的:

#include <iostream> 
#include <functional> 
class B { 
public: 
    std::function<void()> execute{ 
     [](){ 
      std::cout << "Hello World" << std::endl; 
     } 
    }; 
}; 

int main() { 

    B newB; 
    newB.execute(); 
    newB.execute(); 

    newB.execute = [](){std::cout << "FOOBAR\n";}; 

    newB.execute(); 
    return 0; 
} 

其中有相同的輸出。

here是現場演示