Specializing C++ template based on presence/absense of a class member?

后端 未结 2 556
刺人心
刺人心 2020-12-16 23:22

Consider the following:

struct A {
  typedef int foo;
};

struct B {};

template
struct C {};

I wa

相关标签:
2条回答
  • 2020-12-16 23:28

    Something like this might help: has_member.

    typedef char (&no_tag)[1]; 
    typedef char (&yes_tag)[2];
    
    template< typename T > no_tag has_member_foo_helper(...);
    
    template< typename T > yes_tag has_member_foo_helper(int, void (T::*)() = &T::foo);
    
    template< typename T > struct has_member_foo {
        BOOST_STATIC_CONSTANT(bool
            , value = sizeof(has_member_foo_helper<T>(0)) == sizeof(yes_tag)
            ); }; 
    
    template<class T, bool has_foo = has_member_foo<T>::value> 
    struct C {};
    
    0 讨论(0)
  • 2020-12-16 23:31

    Another (C++03) approach:

    template<typename T>
    struct has_foo
    {
    private:
        typedef char no;
        struct yes { no m[2]; };
    
        static T* make();
        template<typename U>
        static yes check(U*, typename U::foo* = 0);
        static no check(...);
    
    public:
        static bool const value = sizeof(check(make())) == sizeof(yes);
    };
    
    struct A
    {
        typedef int foo;
    };
    
    struct B { };
    
    template<typename T, bool HasFooB = has_foo<T>::value>
    struct C
    {
        // T has foo
    };
    
    template<typename T>
    struct C<T, false>
    {
        // T has no foo
    };
    
    0 讨论(0)
提交回复
热议问题