2016-08-02 90 views
0

我已經定義許多對象,併爲它們中的一些,我定義的函數:測試一個不類成員函數存在(SFINAE)

template <typename Ratio> 
auto print(const T &t, bool a= true, bool b= true) 
{ 
    std::stringstream ss; 
    // ... do stuff ... 
    return ss.str(); 
} 

其中T是對象爲其中的一個的類型打印被定義。比率在功能內部使用。

我的問題是: 有沒有辦法讓類型T找到這個函數是否存在?

對於其他用途,我已經使用模板和SFINAE來檢測是否存在類成員方法。但對於我的問題,我找不到解決方案...任何人?

謝謝, 奔

PS:SFINAE的實施例在我的代碼,其中,i需要檢測一個類的成員方法存在使用。

static T none() { ... } 

/** 
* SFINAE for checking id none method exists 
*/ 
template <class T> 
static auto hasNoneMethod(int) 
    -> std::integral_constant<bool, std::is_same<T, decltype(T::none())>::value>; 
template <class> 
static auto hasNoneMethod(...) -> std::false_type; 

/** 
* Type-Function 
*/ 
template <typename T> 
struct HasNoneMethod: decltype(detail::hasNoneMethod<T>(0)) { 
}; 
+1

template 你的意思是T? –

+0

你有一個'typename Ratio'但是使用'T' ...他們是同一個參數嗎?你有嘗試過什麼嗎? – Holt

+0

你是什麼意思?按照它的規定(假設你糾正了你的模板參數名稱錯字),它會自動生成任何你想使用它的類型,因爲它沒有SFINAE約束。 – Smeeheey

回答

1

你可以使用這樣的事情:

template <class T> 
static auto hasPrintMethod(int) 
->std::integral_constant<bool, std::is_class<decltype(print(T()))>::value>; 

template <class> 
static auto hasPrintMethod(...)->std::false_type; 

template <typename T> 
struct HasPrintMethod : decltype(hasPrintMethod<T>(0)) { 
}; 

這裏decltype(print(T()))std::string用於非成員函數定義哪些類,和一個錯誤類型的其他類。因此,根據SFINAE的概念,HasPrintMethod<A>::value等於true對於class Aprint函數定義,否則等於false

+0

非常感謝,看起來您的解決方案有效。 –

相關問題