簡體   English   中英

可能有條件的超載和尾隨返回類型?

[英]Conditional overloading with trailing-return-type possible?

假設您嘗試執行以下操作:

template</* args */>
typename std::enable_if< /*conditional*/ , /*type*/ >::type
static auto hope( /*args*/) -> decltype( /*return expr*/ )
{
}

是否可以將條件包含/重載( std::enable_if )與尾隨返回類型( auto ... -> decltype() )組合在一起?

我不會對使用預處理器的解決方案感興趣。 我總是可以做這樣的事情

#define RET(t) --> decltype(t) { return t; }

並將其擴展為也考慮整個條件。 相反,我感興趣的是該語言是否支持它,而不使用返回類型的其他特征,即ReturnType<A,B>::type_t或函數主體中使用的任何東西。

尾隨返回類型與普通返回類型沒有太大區別,只是在參數列表和cv- / ref-限定符之后指定了該類型。 另外,它不一定需要decltype ,也可以使用普通類型:

auto answer() -> int{ return 42; }

因此,現在您應該看到問題的答案是:

template<class T>
using Apply = typename T::type; // I don't like to spell this out

template</* args */>
static auto hope( /*args*/)
    -> Apply<std::enable_if</* condition */, decltype( /*return expr*/ )>>
{
}

盡管我個人更喜歡僅使用decltype和表達式SFINAE,但條件可以表示為表達式(例如,可以在某種類型的對象上調用函數)嗎:

template<class T>
static auto hope(T const& arg)
  -> decltype(arg.foo(), void())
{
  // ...
}

我只能假設您的原始偽代碼是一個函數模板,否則SFINAE不會完全起作用。 現在,如果它是模板函數,則可以使用默認的其他模板參數,並對該參數使用SFINAE:

template <typename T, typename _ = typename std::enable_if< trait<T>::value >::type >
static auto function( T arg ) -> decltype( expression ) {
   // ...
}

我更喜歡這樣做,因為它將SFINAE限制在template子句中使用,並留下了更簡潔的函數簽名。 這是的C ++ 11我最喜歡下的雷達的新功能之一。

暫無
暫無

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

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