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

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

Consider the following:

struct A {
  typedef int foo;
};

struct B {};

template
struct C {};

I wa

2条回答
  •  Happy的楠姐
    2020-12-16 23:31

    Another (C++03) approach:

    template
    struct has_foo
    {
    private:
        typedef char no;
        struct yes { no m[2]; };
    
        static T* make();
        template
        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::value>
    struct C
    {
        // T has foo
    };
    
    template
    struct C
    {
        // T has no foo
    };
    

提交回复
热议问题