C++ 03 等效于 C++11 lambda

C++ 03 equivalent of C++11 lambda

参考我之前的,需要详细说明。 以下代码片段如何工作,基本和 C++ 03 等效?

 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;

有关 wikipedia or on Whosebug

的更多信息

@Garf365 的回答是最好的。一个 lambda 和一个 class 确实是最相似的——你可以像使用可调用函数一样使用它们,并传递指针和对它们的引用。

但是,您可能还想了解如何使用 函数模板 在编译时完成这项工作,尤其是将它们作为参数传递给另一个模板时,如使用提升库。

我很好奇编译器使用函数模板生成的代码的复杂性是否有所改善,确实有!

自己找:

感谢您提出问题并带领我进行调查!