如何在C++17中使用type_traits检测具有特定名称和签名的函数(NOT类成员)的存在

How to detect the existence of a function (NOT class member) with a specific name and signature using type_traits in C++17

本文关键字:定名称 函数 存在 成员 NOT C++17 type 检测 traits      更新时间:2023-10-16

尝试完成以下操作:

// Template not necessary, but shows the pattern
template <typename T>
bool MyFunction(const T&, const uint8_t);
template <T>
struct is_myfunc_defined : std::false_type{}
// How do I properly create this
template <typname R, typename... Args>
struct is_myfunc_defined<R MyFunction(args....)> : std::true_type
{
};
struct MyStruct1 {};
struct MyStruct2 {};
// Will Match
bool MyFunction(const MyStruct&, const uint8_t){ return true; }
// Will not match
bool ShouldFail1(const MyStruct2&, const uint8_t){ return true; }
void MyFunction(const MyStruct2&, const uint8_t){ return true; }
bool MyFunction(const MyStruct2&){ return true; }
int main()
{
cout << is_myfunc_defined<MyStruct>::value << endl; // true
cout << is_myfunc_defined<MyStruct2>::value << endl; // false
}

我知道如何使用is_detected_class来检查具有特定返回类型、名称和签名的类方法,但如何使用直接函数来检查。想不通,需要帮助。

谢谢!

我知道如何使用is_detected_exact检查类方法

对于全局函数来说没有什么不同:

template <typename ...P>
using detect_myfunc = decltype(MyFunction(std::declval<P>()...));
template <typename T>
struct is_myfunc_defined {};
template <typename R, typename ...P>
struct is_myfunc_defined<R(P...)>
: std::experimental::is_detected_exact<R,detect_myfunc,P...> {};
{};