利用 C/C++ 语言 SFINAE(Substitution Failure Is Not An Error)技术,实现判断类成员函数是否存在。_liulilittle的博客-CSDN博客
新的实现方案:(类成员函数,类成员字段)是否存在判定。
#include <iostream>
#include <type_traits>
// 判定类是否具有特定成员函数的辅助结构体
template<typename T>
struct has_member_function_foo
{
// 默认情况下,假设不存在特定成员函数foo
template<typename U, typename = decltype(std::declval<U>().foo())>
static std::true_type test(int);
// 重载版本,用于捕捉不具有特定成员函数foo的类
template<typename>
static std::false_type test(...);
// 根据函数模板的返回值类型选择对应的重载版本
using type = decltype(test<T>(0));
static constexpr bool value = type::value;
};
// 判定类是否具有特定字段的辅助结构体
template<typename T>
struct has_member_field_bar
{
// 默认情况下,假设不存在特定字段bar
template<typename U, typename = decltype(U::bar)>
static std::true_type test(int);
// 重载版本,用于捕捉不具有特定字段bar的类
template<typename>
static std::false_type test(...);
// 根据函数模板的返回值类型选择对应的重载版本
using type = decltype(test<T>(0));
static constexpr bool value = type::value;
};
// 测试类
struct MyClass1 {
void foo() {}
};
struct MyClass2 {
int bar;
};
int main() {
std::cout << has_member_function_foo<MyClass1>::value << std::endl; // 输出 1
std::cout << has_member_function_foo<MyClass2>::value << std::endl; // 输出 0
std::cout << has_member_field_bar<MyClass1>::value << std::endl; // 输出 0
std::cout << has_member_field_bar<MyClass2>::value << std::endl; // 输出 1
return 0;
}