[英]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.