zoukankan      html  css  js  c++  java
  • CHECK MEMBER TYPE

    检查类里是否存在某种类型的几种方法,以检查xxx类型为例:
    方法1:

    template<class T>
    class has_member_type_Type
    {
        struct big { char a[2]; };
        template<class C> static big  probe(typename C::xxx*); // match here if type T::Type exists
        template<class C> static char probe(...);
    public:
        static const bool value = sizeof(probe<T>(nullptr)) > 1;
    };

    方法2:

    template<typename T, typename = typename T::xxx>
    static std::true_type has_xxx_impl(int);
     
    template<typename T>
    static std::false_type has_xxx_impl(...);
     
    template<typename T>
    struct has_xxx : decltype(has_xxx_impl<T>(0))
    {
    };

    方法3:

    template<typename... Ts> struct make_void { typedef void type; };
    template<typename... Ts> using void_t = typename make_void<Ts...>::type;
     
    template<typename T, typename = void>
    struct has_yyy : std::false_type
    {
    };
     
    template<typename T>
    struct has_yyy < T, void_t<typename T::xxx>> : std::true_type
    {
    };
     
    //用宏简化
    #define HAS_TYPE_MEMBER(MEMBER)
        template<typename T, typename = void>
        struct has_type_##MEMBER : std::false_type
        {
        };
        template<typename T>
        struct has_type_##MEMBER < T, void_t<typename T::MEMBER>>:
        std::true_type
        {
        };
     
        HAS_TYPE_MEMBER(xxx)

    测试代码:

    struct MyStruct
    {
        typedef char xxx;
    };
    
    int main()
    {
        static_assert(has_xxx<MyStruct>::value, "no xxx");
        static_assert(has_type_xxx<MyStruct>::value, "no xxx");
    }
  • 相关阅读:
    iOS拓展---[转载]视频相关,一定要看呀
    iOS拓展---碰到奇葩需求
    iOS拓展---【转载】成熟的夜间模式解决方案
    2018年度总结
    linux常用命令
    自我认识
    SpringBoot入门最详细教程
    SVN分支的合并和同步
    java Data、String、Long三种日期类型之间的相互转换
    徐胜治:我要留下真正的东西
  • 原文地址:https://www.cnblogs.com/qicosmos/p/4929393.html
Copyright © 2011-2022 走看看