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

后端 未结 7 2156
花落未央
花落未央 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:08

    A modification of Potatoswatter's answer

    Works on gcc-4.6

    #include 
    
    template< class T >
    struct identity {
    typedef T type;
    };
    
    template
    struct if_c : identity {};
    
    template< typename T, typename F>
    struct if_c : identity {};
    
    template
    struct if_ : if_c< Bool::value, T, F> {};
    
    template< class T >
    struct is_default_constructible_;
    
    template< class T >
    struct is_default_constructible :
      if_< std::is_arithmetic,
        std::true_type,
        is_default_constructible_ >::type { };
    
    
    template< class T >
    struct is_default_constructible_ {
    
        template class Acessible : public D
        {
          friend class is_default_constructible_;
          public:
          //using D::D; may be needed once N2540 is implemented 
        };
    
        template
        class receive_size{};
    
        template< class U >
        static int sfinae( receive_size< sizeof Acessible() > * );
    
        template< class U >
        static char sfinae( ... );
    
    public:
        enum { value = sizeof( sfinae(0) ) == sizeof(int) };
    
    };
    
    struct p { p(); };
    class q { q(); };
    class r { r(int); };
    
    #include 
    using namespace std;
    
    int main() {
        cerr << is_default_constructible::value << endl // outputs 1
            << is_default_constructible

    ::value << endl << is_default_constructible::value << endl << is_default_constructible::value << endl; // outputs 0 }

    # g++-mp-4.6 --std=c++0x -Wall test.cpp && ./a.out
    1
    1
    0
    0

提交回复
热议问题