Detect existence of private member

后端 未结 2 1335
萌比男神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 21:07

    There is indeed a way for non-final non-union class types:

    namespace detail {
        struct P {typedef int member;};
        template 
        struct test_for_member : U, P
        {
            template 
            static std::false_type test(int);
            static std::true_type test(float);
        };
    }
    template 
    using test_for_member =
      std::integral_constant::test(0)){}>;
    

    Demo. The trick is to check whether lookup into different base classes will yield an ambiguity. [class.member.lookup]/2:

    Member name lookup determines the meaning of a name (id-expression) in a class scope (3.3.7). Name lookup can result in an ambiguity, in which case the program is ill-formed. […] Name lookup takes place before access control (3.4, Clause 11).

    Note that GCCs lookup is broken insofar as it ignores non-type names for lookup in typename-specifiers.

提交回复
热议问题