Is there a way to test whether a C++ class has a default constructor (other than compiler-provided type traits)?

后端 未结 7 2157
花落未央
花落未央 2020-11-28 13:00

Traits classes can be defined to check if a C++ class has a member variable, function or a type (see here).

Curiously, the ConceptTraits do not include traits to che

7条回答
  •  一个人的身影
    2020-11-28 13:24

    After shedding much blood, sweat, and tears, I finally found a way that works on every compiler I tried:

    template struct is_default_constructible;
    
    template<> struct is_default_constructible
    {
    protected:
        // Put base typedefs here to avoid pollution
        struct twoc { char a, b; };
        template struct test { typedef char type; };
    public:
        static bool const value = false;
    };
    template<> struct is_default_constructible<>::test { typedef twoc type; };
    
    template struct is_default_constructible : is_default_constructible<>
    {
    private:
        template static typename test::type sfinae(U*);
        template static char sfinae(...);
    public:
        static bool const value = sizeof(sfinae(0)) > 1;
    };
    

提交回复
热议问题