1

我正在尝试检查模板参数是否存在默认构造函数。我想做这样的事情:

template <typename A>
class Blah
{
   Blah() { A* = new A(); } 
}

但是我想在编译时通过SFINAE或其他技巧检测该构造函数是否存在,如果static_assert不存在,则提出我自己的 a 。

当我的类(例如std::vector)没有“默认构造函数”但具有默认参数的构造函数时,就会出现问题。

所以使用std::has_trivial_default_constructor不会返回true。虽然我可以使用new vector<T>().

4

2 回答 2

6

这是类型特征的可能实现:

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
}
于 2012-12-09T10:46:41.183 回答
4

C++ 标准中没有std::has_trivial_default_constructor;这似乎是来自 Boost 的 gcc 增强。这不是你想要的。您不想检查某些东西是否具有微不足道的默认构造函数;您想检查某个类是否具有默认构造函数,无论是否微不足道。使用std::is_default_constructible(假设一个 c++11 兼容编译器)。

于 2012-12-09T10:43:40.950 回答