問題保持不變 - 我們能否檢測到重載的成員函數,但沒有指定它們的參數或使用提到的技巧?我知道我可能是要求不可能的,但它永遠不會受到傷害要求
實際上,這不是不可能的。
它遵循最小,工作示例:
template<typename T, typename R, typename... A>
void proto(R(T::*)(A...));
template<typename, typename = void>
constexpr bool has_single_f = false;
template<typename T>
constexpr bool has_single_f<T, decltype(proto(&T::f))> = true;
struct S {
void f(int) {}
void f(char) {}
};
struct U {
void f() {}
};
int main() {
static_assert(not has_single_f<S>, "!");
static_assert(has_single_f<U>, "!");
}
當然,你需要添加更多的東西成員方法和數據成員來區分,但它是微不足道的添加它們(見頭type_traits
),我試過儘可能減少示例。
其基本思想是如果給定函數過載,則調用proto
失敗,因爲它是模糊呼叫。
無論如何,由於SFINAE規則,該錯誤被丟棄。
參數不需要根據請求指定。
另請注意,proto
不需要定義,但重要的是其返回類型爲void
。否則,您必須調用稍微修改,以decltype
因爲它遵循:
template<typename T>
constexpr bool has_single_f<T, decltype(proto(&T::f), void())> = true;
正如你從示例代碼中看到,static_assert
■確認f
在S
超載,這是不是在U
。
上述示例基於模板變量,它們是自C++ 14以來的語言的一部分。
如果你喜歡衆所周知基礎結構解決方案,它與C++ 11的作品,你可以使用下面的檢測:
#include<type_traits>
//...
template<typename, typename = void>
struct has_single_f: std::false_type {};
template<typename T>
struct has_single_f<T, decltype(proto(&T::f))>: std::true_type {};
//...
int main() {
static_assert(not has_single_f<S>::value, "!");
static_assert(has_single_f<U>::value, "!");
}
有趣的問題,這很有趣,以找到一個方法來做到這一點。 +1 – skypjack