簡體   English   中英

函數g ++ 6.2的自動類型推導

[英]auto type deduction for function g++ 6.2

我正在嘗試使用現代C ++“自動”,並找到了一個產生錯誤的簡單示例,但我不明白為什么:

main.cpp

// error: use of ‘auto test(int)’ before deduction of ‘auto’ int i = test(5);
int i = test(5);

測試

auto test(int i);

測試文件

auto test(int i) {
  if (i == 1)
    return i;               // return type deduced as int
  else
    return Correct(i-1)+i;  // ok to call it now
}

但是,如果我使用'->'指定類型,則代碼會構建並運行良好。 例如:

auto test(int i) -> int;

g ++ 6.2是編譯器的現代版本,我想知道為什么我必須使用'-> int'。 感謝您的建議。

返回類型推論根本不能用於聲明。 編譯器使用定義(實現)通過檢查函數實際返回的內容來推斷類型。 在聲明中無法執行此操作,因此在調用該函數時編譯將失敗,因為尚無推定的返回類型。

當使用尾隨返回類型時,可以顯式指定返回類型。 在您的情況下,這與使用舊的“正常”聲明返回類型的方式沒有什么不同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM