Detect if a default constructor exists at compile time [duplicate]

这一生的挚爱 提交于 2019-11-28 14:30:29

Here's a possible implementation of the type trait:

template<typename T>
class is_default_constructible {

    typedef char yes;
    typedef struct { char arr[2]; } no;

    template<typename U>
    static decltype(U(), yes()) test(int);

    template<typename>
    static no test(...);

public:

    static const bool value = sizeof(test<T>(0)) == sizeof(yes);
};

struct foo {
    foo(int) {}
};

int main()
{
    std::cout << is_default_constructible<foo>::value << '\n'        // 0
              << is_default_constructible<std::vector<int>>::value;  // 1
}

There is no std::has_trivial_default_constructor in the C++ standard; this appears to be a gcc enhancement that came from Boost. This is not what you want. You don't want to check if something has a trivial default constructor; you want to check if some class has a default constructor, trivial or not. Use std::is_default_constructible (assuming a c++11 compliant-compiler).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!