[英]What is the purpose of the declaration “template auto A::f(int t) -> decltype(t + g())”
[英]What happens if we use “decltype(auto) f()” as a function declaration with “decltype(f()) result” in the definition?
這確實是一個C ++ 14問題。 而且它比理論上更不實際。
有時,您會逐步構建函數的結果:
int f( int x, int y )
{
int a;
//...
return a;
}
但是如果您更改返回類型,則也必須更改“ a”的類型。 我通過一個特殊的聲明解決了這個問題:
int f( int x, int y )
{
decltype( f(x,y) ) a;
//...
return a;
}
(對於新手:函數參數使用r值引用會帶來什么陷阱?提示:我們需要std::forward
來解決它。)一個隨機出現的問題浮現在腦海:如果我使用新的C ++會怎樣? 14“ decltype( auto )
”功能作為返回類型? 我們會得到遞歸的黑洞嗎? 還是不允許的錯誤? 將初始化程序添加到“ a”會使一切正常嗎?
一個問題隨機出現在我的腦海:如果我使用“ decltype(auto)”的新C ++ 14功能作為返回類型怎么辦?
OP引用的示例是:
auto f( int x, int y ) // using C++1y's return type deduction
{
decltype( f(x,y) ) a;
//...
return a;
}
我們會得到遞歸的黑洞嗎? 還是不允許的錯誤?
不允許[dcl.spec.auto] / 11:
如果需要使用具有未推導的占位符類型的實體的類型來確定表達式的類型,則程序格式錯誤。 但是,一旦在函數中看到了return語句,從該語句推斷出的返回類型就可以在該函數的其余部分中使用,包括在其他return語句中。
將添加一個初始值設定
a
讓一切都還了吧?
防爆。
decltype( f(x,y) ) a = 42;
沒有; 使用decltype
需要確定f
的返回類型。 但是,以下是可能的:
auto a = 42;
來自評論:
所以我可以在函數的開頭有一個
if
&return
塊,然后在以后使用decltype(f(X))
構造(對於函數的其余部分)?
是的,例如
auto f( int x, int y ) // using C++1y's return type deduction
{
if(false) return int();
decltype( f(x,y) ) a;
//...
return a;
}
但是,我寧願:
auto f( int x, int y ) // using C++1y's return type deduction
{
int a; // specifying the return type of `f` here
//...
return a;
}
要么
auto f( int x, int y ) // using C++1y's return type deduction
{
auto a = 42; // specifying the return type of `f` via the initializer
//...
return a;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.