比方說,我有一個模板函數返回一個依賴類型。喜歡的東西:typedefing函數返回類型
template <class T>
typename std::result_of<T()>::type
foo()
{
std::result_of<T()>::type retVal;
// Some mind blowing code...
return retVal;
}
正如你所看到的,我聲明的返回值的局部變量時,曾在函數類型寫的返回類型兩次,一次,另一次。
有沒有一種方法我可以typedef
這種類型的函數簽名,所以類型將只聲明一次(無代碼複製),並且只在函數(簽名和正文)內可見和可用? 喜歡的東西(警告僞代碼未來,請不要生氣或啓發!):
template <class T>
typedef typename std::result_of<T()>::type FooReturnType
FooReturnType foo()
{
FooReturnType retVal;
// Some mind blowing code...
return retVal;
}
編輯:我是僅限於C++編譯器11。
感謝
嘗試將其作爲默認模板參數 – user3514538
或者如果您的編譯器支持C++ 14,可能是自動返回類型? – oLen
@ user3514538想過它......但是然後調用者將能夠覆蓋此值。我需要'static_assert',第二個參數確實是我想要的(仍然需要寫兩次返回類型...):( –