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

问题描述 投票:0回答:1

试图完成以下任务:

// 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_exact来检查具有特定返回类型,名称和签名的类方法,但是如何使用简单函数来做到这一点。无法解决,需要帮助。

谢谢!

c++ c++17 typetraits
1个回答
2
投票

我知道如何使用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...> {};
{};
© www.soinside.com 2019 - 2024. All rights reserved.