c++ - 函数中的自动参数类型

标签 c++ c++14 auto c++17

我想知道标准委员会是否考虑扩展 C++14 auto 关键字来推断函数模板参数类型,因为它目前存在于通用 lambda 中。 ( as can be seen nicely depicted in this answer )

因为它适用于 lambda 函数,所以它也应该适用于任何函数。当然,对于经典语法来说,这完全是多余的:

template< typename T >
void f(T param);

但是为了同样的结果能够写这个:

void f(auto param);

我认为可以减少阻塞代码(更短更整洁的清洁器)并在这个用例中实现很好的一致性:

auto v = func1();
f(v);

如您所见,我们使用了自动类型推导器来声明 v,但随后我们必须使用硬类型参数化函数 f 或模板化 f。
结合 auto 我们应该使用 auto,这样会更一致。

编辑:this question确实有效地询问了同样的事情,但不那么直接。还没有得到 user657267 给出的答案,我在下面复制和扩展。

最佳答案

好的,感谢 Piotr 指出了另一个问题,询问同样的事情,我在评论中找到了可以解决这个问题的信息,这里是:

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4040.pdf

第 16 页,第 5.1.1 章命名泛型函数

A generic function is a function template whose template-parameter-list has a parameterdeclaration whose type-specifier is either auto or a constrained-type-name.

[ Example:

auto f(auto x); // Ok
void sort(C& c); // Ok (assuming C names a concept)

— end example ]

这看起来相当积极:)

后跟预期的明显措辞,匹配通用 lambda:

The declaration of a generic function has a template-parameter-list that consists of one invented type template-parameter for each occurrence of auto.

[ Example: The following generic function declarations are equivalent:

template<typenaem T>  
conxtexpr bool C() { ... }  
auto f(auto x, const C& y);  
template<typename T1, C T2> 
auto f(T1 x, const T2& y);

The type of y is a type parameter constrained by C. — end example ]

关于c++ - 函数中的自动参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31648458/

相关文章:

c++ - 将函数指针类型转换为对应的字符串

c++ - constexpr 和 CRTP : compiler disagreement

c++ - 为什么在 C++11/C++14 中有针对自动和大括号初始化器的特殊类型推导规则?

c++ - Foreach 范围迭代 vector<int> - auto 或 auto&?

c++ - 使用 XSendEvent 传递鼠标事件

c++ - 遍历内存以读取值

c++ - 多级 c/c++ 宏 - 评估结果后的空格?

c++ - 自定义链表 C++ 中的内存泄漏

C++ 语法 : return statement with space after "template"; what does it mean

"Android auto"应用程序中未显示 Android 汽车音乐应用程序