Possible to use type_traits / SFINAE to find if a class defines a member TYPE?

前端 未结 3 1730
甜味超标
甜味超标 2020-12-29 09:19

I have seen this question which allows one to check for the existence of a member function, but I\'m trying to find out whether a class has a member

3条回答
  •  长发绾君心
    2020-12-29 09:37

    I prefer to wrap it in macro.

    test.h:

    #include 
    
    template
    struct void_type
    {
         using type = void;
    };
    
    template
    using void_t = typename void_type::type;
    
    #define HAS_TYPE(NAME) \
    template \
    struct has_type_##NAME: std::false_type \
    {}; \
    template \
    struct has_type_##NAME>: std::true_type \
    {} \
    
    HAS_TYPE(bar);
    

    test.cpp:

    #include 
    
    struct foo1;
    struct foo2 { typedef int bar; };
    
    int main()
    {
        std::cout << has_type_bar::value << std::endl;
        std::cout << has_type_bar::value << std::endl;
        return 0;
    }
    

提交回复
热议问题