[英]What does the C++14 standard say regarding auto as argument type
让我们看看下面的代码:
#include <iostream>
class Test
{
private:
int x;
public:
Test(int _x) :
x(_x)
{
std::cout << "Im being constructed" << std::endl;
}
int getx()
{
return this->x;
}
friend std::ostream& operator<<(std::ostream& os, Test& other)
{
os << other.getx();
return os;
}
};
auto func(auto x)
{
std::cout << x << std::endl;
return x.getx();
}
int main()
{
auto y = func(20);
return 0;
}
编译器如何确定(20)是int还是Test对象? Test的构造函数不明确,那么标准对它有何看法?
因此,虽然gcc允许auto作为函数中的参数,但这不是C ++ 14的一部分,而是根据Herb Sutter上一次旅行报告可能成为C ++ 1z的一部分的概念 - lite的 一部分 。
我相信gcc允许这作为扩展,如果我们使用-pedantic
gcc编译你的程序将警告:
warning: ISO C++ forbids use of 'auto' in parameter declaration [-Wpedantic]
auto func(auto x)
^
因此,从概念精简提案中我们可以看到:
auto func(auto x)
{
std::cout << x << std::endl;
return x.getx();
}
相当于:
template <typename T1>
auto func(T1 x)
{
std::cout << x << std::endl;
return x.getx();
}
因此x
将推断为int 。 编译器将正确地给你一个错误,如gcc中的以下错误( 请参见实时 ):
error: request for member 'getx' in 'x', which is of non-class type 'int'
return x.getx();
^
这在提案部分5.1.1
[dcl.fct]中有所介绍 :
在parameter-declaration-clause中使用auto或concept-name应解释为使用具有相同约束和命名概念的类型参数。 [注意:实现这一目标的确切机制尚未明确。 -end note] [示例:下面声明的泛型函数
auto f(auto x, const Regular& y);
相当于以下声明
template<typename T1, Regular T2> auto f(T1 x, const T2&);
- 末端的例子]
auto
as argument类型的规则与模板参数的规则相同。
auto func(auto x)
相当于template<typename T> auto func(T x)
不过,我不是律师引用特定规则的标准。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.