Skip to content

Question about Chapter 3 Generic Lambda #242

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
bLueriVerLHR opened this issue Jul 16, 2022 · 1 comment
Closed

Question about Chapter 3 Generic Lambda #242

bLueriVerLHR opened this issue Jul 16, 2022 · 1 comment
Labels

Comments

@bLueriVerLHR
Copy link

问题描述

第二章在 auto 关键字中说明并展示了 C++20 中在参数列表里使用 auto 构成一定意义上的模板函数。但是在第三章的泛型 Lambda 中却说到 auto 不能作为形式参数的类型。在不指明版本的时候,是否会产生叙述上的矛盾?尤其本书目标在于C++11/14/17/20 多个版本。

因为刚开始学习 modern C++,所以对在读到上述内容的时候产生了比较大的困惑。

同时也有我个人不确定的内容。

在 C++14 可以使用变量模板的方式对 Lambda 函数添加模板参数。不过没有隐式类型推导,需要在参数列表中指明。例如:

template <typename TL, typename TR>
auto func = [](const TL &l, const TR &r) noexcept -> decltype(l + r) {
    return l + r;
};

int main() {
    func<int, long>(1, 2);
    return 0;
}

这个是否会和 Lambda 表达式并不能够模板化 的叙述产生矛盾?

@changkun
Copy link
Owner

可能是这里的表述有些许误导,这样更改应该容易消除误解:

上一节中我们提到了 `auto` 关键字不能够用在参数表里,这是因为这样的写法会与模板的功能产生冲突。
但是 Lambda 表达式并不是普通函数,所以在没有明确指明参数表类型的情况下,Lambda 表达式并不能够模板化。
幸运的是,这种麻烦只存在于 C++11 中,从 C++14 开始,Lambda 函数的形式参数可以使用 `auto`
关键字来产生意义上的泛型:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants