首页 > 解决方案 > 当 C++14 已经有泛型 lambda 时,在 C++20 中引入模板 lambda 的需要是什么?

问题描述

引入了通用 lambda,使得编写以下内容成为可能:

auto func = [](auto a, auto b){
    return a + b;
};
auto Foo = func(2, 5);
auto Bar = func("hello", "world");

很明显,这个通用 lambdafunc就像模板函数func一样工作。

为什么 C++ 委员会决定为泛型 lamda 添加模板语法?

标签: c++c++14c++20generic-lambda

解决方案


C++14 泛型 lambda 是一种非常酷的方式来生成具有operator ()如下所示的仿函数:

template <class T, class U>
auto operator()(T t, U u) const;

但不是这样:

template <class T>
auto operator()(T t1, T t2) const; // Same type please

也不是这样:

template <class T, std::size_t N>
auto operator()(std::array<T, N> const &) const; // Only `std::array` please

也不是这样(尽管实际使用起来有点棘手):

template <class T>
auto operator()() const; // No deduction

C++14 lambda 很好,但 C++20 允许我们轻松实现这些情况。


推荐阅读