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

后端 未结 7 2129
花落未央
花落未央 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<class T = void> struct is_default_constructible;
    
    template<> struct is_default_constructible<void>
    {
    protected:
        // Put base typedefs here to avoid pollution
        struct twoc { char a, b; };
        template<bool> struct test { typedef char type; };
    public:
        static bool const value = false;
    };
    template<> struct is_default_constructible<>::test<true> { typedef twoc type; };
    
    template<class T> struct is_default_constructible : is_default_constructible<>
    {
    private:
        template<class U> static typename test<!!sizeof(::new U())>::type sfinae(U*);
        template<class U> static char sfinae(...);
    public:
        static bool const value = sizeof(sfinae<T>(0)) > 1;
    };
    
    0 讨论(0)
提交回复
热议问题