为什么不允许auto作为函数参数? [英] Why auto is not allowed as function argument?

查看:697
本文介绍了为什么不允许auto作为函数参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自这个问题,很显然 auto 不能用作函数参数。我的问题是为什么返回类型允许为 auto 但函数参数不允许?

From this question, it is clear that auto cannot be used as function argument. My question is why return type is allowed as auto but function arguments are not ?

auto function(auto data)
{
    //DOES something
}

因为,有很多好处 c ++ 1z 中的 auto 中,为什么不这样做?

Since, there are many benefits of auto coming in c++1z, then why not this ?

推荐答案

此语法是在Concepts TS中提出的,对于各种原因

This syntax was proposed in the Concepts TS, which did not make it into C++17 for various reasons.

尽管我在下面概述了一些批评,但它已在C ++ 20中添加。

Despite some critique I've outlined below, it has been added in C++20.

注意:通过将P1141R2合并到标准中,已使答案的以下部分过时。

但是,即使我们最终在下一次迭代中获得了Concepts(可能是C ++ 20),它仍然是不清楚所需的语法将使其成为标准。在本文中,Richard Smith和James Dennett批评了所谓的 Terse模板符号 ,说

However, even if we finally get Concepts in the next iteration (probably C++20), it is not clear the desired syntax will make it into the standard. In this paper, Richard Smith and James Dennett critique the so called "Terse template notations", saying


Concepts TS引入了太多语法用于功能模板声明。其中一些语法没有用于模板的清晰,一致的语法标记,这对于代码阅读者来说是重要的语义信息(请记住,代码的阅读量远大于所编写的内容)。

The Concepts TS introduces too many syntaxes for a function template declaration. Some of those syntaxes have no clear, consistent syntactic marker for templates, which is important semantic information for the reader of the code (remembering that code is read vastly more than it is written).

他们继续提出不同的语法以实现目标,同时保持模板声明更加一致:

They go on to propose a different syntax to achieve the goal, while keeping template declarations more consistent:


=>要求使用明确的符号将函数声明为模板

=> Require an explicit sigil to declare a function to be a template

替换

void f(auto a) {}
template<typename T> void g(auto a) {}

with

template<...> void f(auto a) {}
template<typename T, ...> void g(auto a) {}

中的... template-parameter-list 表示将从声明中推断出
个附加模板参数。

The ​...​ sigil in the ​template-parameter-list indicates that additional template parameters will be inferred from the declaration.

所以 Tl; dr :与标准化过程相关的原因有很多,为什么我们在C ++ 17中没有它,还有更多原因我们可能永远都不会得到。如果我对论文的理解正确,关键是每个模板都应使用 template 关键字引入。

So Tl;dr: There are a bunch of reasons related to the standardization procedure why we don't have it in C++17, and there are more reasons why we probably won't ever get it. If I understood the paper correctly, the key point being that every template should be introduced with a template keyword.

这篇关于为什么不允许auto作为函数参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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