2017-05-29 39 views
-2

我有一個庫,它是用C++ 11標準(至少)編寫的,我的編譯器是C++ 0x。 庫包含一些函數,我必須恢復到C++ 0x。 因爲我有lambda表達式沒有經驗,我停留在重寫以下功能:如何重寫函數,而不使用lambda表達式?

void EventTrace::connect(Connector& connector) 
{ 
    Connector::EventSignal& s = connector.getEventSignal(); 
    connection_ = s.connect(
     [this](int e) 
     { 
      if (decoders_.empty()) 
      { 
       poco_information_f1(LOGGER(), "Event %d", e); 
      } 
      for (Decoder decoder : decoders_) 
      { 
       try 
       { 
        decoder(e); 
       } 
       catch (Exception& exception) 
       { 
        poco_warning_f1(LOGGER(), "EventTrace Decoder error %s", exception.displayText()); 
       } 
      } 
     } 
    ); 
} 

任何幫助表示讚賞。

+0

你可能想澄清你的問題:什麼是你想達到什麼目的?你嘗試了什麼?代碼看起來不錯,爲什麼要重寫它? – anatolyg

+0

讓我明白:你想將C++ 11代碼轉換爲C++ 0x代碼嗎? – max66

+0

是的,我需要將C++ 11代碼轉換爲C++ 0x,因爲我有C++ 0x編譯器。升級編譯器不是一種選擇,因爲它是更多的工作,老年人不希望這樣做。 – Timo

回答

4

lambda只是(在C++中)一個匿名結構/類的operator()周圍的語法糖。

在預C++ 11的代碼,你可以通過這些結構的一個替代的λ,例如:

struct Foo { 
    Foo(EventTrace* e): e_(e) {} 
    void operator()(int t) { 
     // the inside of the lambda 
     // you just have to replace implicit usage of this by e_->... 
    } 
}; 
void EventTrace::connect(Connector& connector) 
{ 
    Connector::EventSignal& s = connector.getEventSignal(); 
    Foo f(this); 
    connection_ = s.connect(f); 
} 
+0

您的運營商()有錯誤的簽名,應採取int。 –

+0

是的,它應該,謝謝你的更正。 – nefas