利用 C/C++ 语言 SFINAE(Substitution Failure Is Not An Error)技术,实现判断类成员函数(Method)、成员字段(Field)是否存在。

利用 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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值