參考我以前的question,因爲需要詳細解釋。 以下代碼片段如何工作,基本和C++ 03等效?C++ 03等效的C++ 11 lambda
auto get_option_name = [](const std::pair<const std::string, std::string>& p) -> const std::string& {
return p.first;
};
參考我以前的question,因爲需要詳細解釋。 以下代碼片段如何工作,基本和C++ 03等效?C++ 03等效的C++ 11 lambda
auto get_option_name = [](const std::pair<const std::string, std::string>& p) -> const std::string& {
return p.first;
};
它等同於:
class Extractor {
// Definition of "function call" operator, to use instance
// of this class like a function
const std::string& operator()(const std::pair<const std::string, std::string>& p) {
return p.first;
}
};
Extractor get_option_name;
@ Garf365的回答是最好的。一個lambda和一個像這樣的類真的是最相似的 - 你可以像調用函數一樣使用它們,並傳遞指針和對它們的引用。
但是,您可能還想了解如何使用功能模板在編譯時執行此項工作,尤其是在將它們作爲參數傳遞到另一個模板時(如使用boost庫)。
我很好奇,如果編譯器通過使用函數模板生成的代碼的複雜性有了改進,那麼!
看一下吧:
謝謝你提出這個問題,並帶領我去研究它!
它是一個仿函數,即一個像函數一樣工作的對象。看[這裏](http://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11) – sp2danny