当C ++ 14已经具有通用lambda时,在C ++ 20中引入的模板lambda有什么需求? [英] What is the need of template lambda introduced in C++20 when C++14 already has generic lambda?

查看:82
本文介绍了当C ++ 14已经具有通用lambda时,在C ++ 20中引入的模板lambda有什么需求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

引入了通用lambda,从而可以编写以下代码:

c++14 introduced generic lambdas that made it possible to write following:

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

很明显,此通用lambda func的工作方式与模板化函数func的工作方式一样.

It is very clear that this generic lambda func works just like a templated function func would work.

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

Why did the C++ committee decide to add template syntax for generic lamda?

推荐答案

C ++ 14通用lambda是一种非常酷的方法,可以使用如下所示的operator ()生成函子:

C++14 generic lambdas are a very cool way to generate a functor with an operator () that looks like this:

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

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

Nor like this (although this gets a bit tricky to actually use):

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

C ++ 14 lambdas很好,但是C ++ 20允许我们轻松地实现这些情况.

C++14 lambdas are fine, but C++20 allows us to implement these cases without hassle.

这篇关于当C ++ 14已经具有通用lambda时,在C ++ 20中引入的模板lambda有什么需求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆