8

GCC允许以下语法作为扩展:

// a functional object that will add two like-type objects
auto add = [] <typename T> (T a, T b) { return a + b; };

在2012 年通用 lambda 提案n3418中,我们看到了允许上述内容的语法:

overload( []<class T>(T* p) {...},

然而,由于它是一个扩展,语法显然不存在(或不允许)。在什么情况下,当我们有 auto 时,上面的内容会有用,为什么语法不存在(或不允许)?

4

1 回答 1

10

在我看来,C++14 的多态 lambda 更加简洁。

您可以重现示例情况的效果,如下所示:

struct A {};
struct B {};

int operator+(A, A) { return 1; }
int operator+(B, B) { return 2; }
int operator+(A, B) { return 3; }
int operator+(B, A) { return 4; }

int main() {
    auto add = [](auto a, decltype(a) b) { return a + b; };
    auto flexible_add = [](auto a, auto b) { return a + b; };

    add(A{}, A{});  // works
    add(B{}, B{});  // works
    add(A{}, B{});  // doesn't work

    flexible_add(A{}, A{});  // works
    flexible_add(B{}, B{});  // works
    flexible_add(A{}, B{});  // works

    auto deref = [](auto *a) { return *a; };
    int foo{};
    A a;
    B b;
    deref(&foo); // works
    deref(&a);   // works
    deref(&b);   // works
    deref(foo);  // doesn't work
    deref(a);    // doesn't work
    deref(b);    // doesn't work
}

尽管在许多情况下 GCC 扩展功能更强大,不仅在您的用例中(它更自然地适合)。例如,关于非类型模板参数:

#include <cstddef>
#include <utility>
#include <iostream>

void print(std::initializer_list<std::size_t> il)
{
    for (auto&& elem : il) std::cout << elem << std::endl;
}

int main()
{
    auto indexed_lambda = [] <std::size_t... Is> (std::index_sequence<Is...>) { print({Is...}); };

    indexed_lambda(std::make_index_sequence<5>{});    
}

科利鲁

复杂的泛型参数类型:

void foo() {}

int main() {
    auto accept_no_args_fun_only = [] <typename R> (R (*)()) {};

    accept_no_args_fun_only(foo);
}

科利鲁

可变参数:

#include <tuple>
#include <vector>

int main() {
    auto accept_vector = [] (std::vector<auto> &&) {}; // Unconstrained placeholder from Concept TS, but not variadic
    auto accept_tuple = [] <typename... Args> (std::tuple<Args...> &&) {};

    accept_vector(std::vector{42});
    accept_tuple(std::tuple{42});
}

科利鲁

我不知道涉及包含泛型 lambda 的讨论,但我可以看到有人在思考,当当前语法涵盖大多数用例、简洁且适合 lambda 的意图时,这种扩展是否值得包括在内,这通常用于生成简短的代码片段。

编辑

在第一次 C++20 ISO 标准会议上,GCC 扩展已决定成为 C++ 的一部分:

于 2014-10-19T20:05:13.003 回答