Detect existence of private member

后端 未结 2 1327
萌比男神i
萌比男神i 2020-12-29 20:27

I want to write a type trait to check if some type has a member member. If member were public, there are any number of ways to do this (e.

2条回答
  •  庸人自扰
    2020-12-29 20:58

    You can create another class MemberBase that does have that member, and then subclass the two classes (the class to check T and BaseMember) and try to access the member of the subclass. If T also has a member member, then you will get an ambiguity problem.

    Code:

    #include 
    
    // Yakk's can_apply
    
    templatestruct voider{using type=void;};
    templateusing void_t=typename voider::type;
    
    templatestruct types{using type=types;};
    namespace details {
      templateclass Z, class types, class=void>
      struct can_apply : std::false_type {};
      templateclass Z, class...Ts>
      struct can_apply< Z, types, void_t< Z > >:
        std::true_type
      {};
    }
    templateclass Z, class...Ts>
    using can_apply = details::can_apply>;
    
    // Main code
    
    class MemberBase {
        public:
            int member;
    };
    
    template
    class MemberCheck: public ToCheck, public MemberBase {
    };
    
    template 
    using member_type = decltype(&T::member);
    
    template 
    using hasnot_member = can_apply>;
    
    template  
    using static_not = std::integral_constant;
    
    template 
    using has_member = static_not>;
    
    // Tests
    
    class A {
        int member;
    };
    
    class Ap {
        public:
        int member;
    };
    
    class B {
        float member;
    };
    
    class C {
        int member();
    };
    
    class D {
    };
    
    static_assert(has_member{}, "!"); // ok
    static_assert(has_member{}, "!"); // ok
    static_assert(has_member{}, "!"); // ok
    static_assert(has_member{}, "!"); // ok
    static_assert(has_member{}, "!"); // fail
    

    However, this definitely smells like a dirty hack to me.

提交回复
热议问题