c++ - 引入 lambda 后,类内部函数是否有任何用例?

标签 c++ c++11 nested-class lambda

来自wikipedia关于 Lambda 函数和表达式的文章:

users will often wish to define predicate functions near the place where they make the algorithm function call. The language has only one mechanism for this: the ability to define a class inside of a function. ... classes defined in functions do not permit them to be used in templates

这是否意味着在 C++0x lambda 就位后,在函数内部使用嵌套结构将被默默弃用?

另外,上段最后一行是什么意思?我知道嵌套类不能是template;但那句话并不意味着。

最佳答案

我不确定我理解你的困惑,但我会陈述所有事实,让你理清头绪。 :)

在 C++03 中,这是合法的:

#include <iostream>

int main()
{
    struct func
    {
        void operator()(int x) const
        {
            std::cout << x << std::endl;
        }
    };

    func f; // okay
    f(-1); // okay

    for (std::size_t i = 0; i < 10; ++i)
        f(i) ; // okay
}

但如果我们尝试这样做,它不是:

template <typename Func>
void exec(Func f)
{
    f(1337);
}

int main()
{
    // ...

    exec(func); // not okay, local classes not usable as template argument
}

这给我们留下了一个问题:我们想定义谓词以用于此函数,但我们不能将其放在函数中。所以我们必须将它移动到任何外部范围并在那里使用它。这不仅让其他人不需要知道的东西弄得乱七八糟,而且把谓词从使用它的地方移开,使代码更难阅读。

对于函数偶尔重复使用的代码块,它仍然有用(例如,在上面的循环中;您可以使用函数谓词来判断一些复杂的事物及其参数),但大多数时候我们想在模板中使用它们。

C++0x 更改规则以允许上述代码工作。他们还添加了 lambdas:用于将函数对象创建为表达式的语法,如下所示:

int main()
{
    // same function as above, more succinct
    auto func = [](int x){ std::cout << x << std::endl; };

    // ...
}

这和上面的完全一样,但是更简单。那么“真正的”本地类(class)还有用吗?当然。毕竟,Lambda 的功能还不够完善:

#include <iostream>

template <typename Func>
void exec(Func func)
{
    func(1337);
}

int main()
{
    struct func
    {
        // note: not possible in C++0x lambdas
        void operator()(const char* str) const
        {
            std::cout << str << std::endl;
        }

        void operator()(int val) const
        {
            std::cout << val << std::endl;
        }
    };

    func f; // okay
    f("a string, ints next"); // okay

    for (std::size_t i = 0; i < 10; ++i)
        f(i) ; // okay

    exec(f); // okay
}

也就是说,对于 lambda,您可能不会再看到本地类了,但原因完全不同:一个几乎没用,另一个几乎被取代。

关于c++ - 引入 lambda 后,类内部函数是否有任何用例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6868768/

相关文章:

c++ - 意外的 fork 行为

c++ - 使用空大括号初始化程序 : pointer or reference? 的重载分辨率

c++ - 如何设置默认参数以防用户未输入另一个参数

java - 嵌套类占用更多内存空间?

c# - linq嵌套列表包含

java - 静态嵌套类实例

c++ - 当包含对象包含 unique_ptr 时如何删除 vector 的元素?

c++ - 如何在 Windows 上为 Qt 安装 OpenSSL 1.1.0?

python - SWIGging Boost.Geometry 时出现 "Syntax error in input"?

c++ - 为可变参数模板编写基本案例