std::is_default_constructible 错误,如果构造函数是私有的

2024-01-26

我有以下片段

#include <type_traits>
#include <boost/type_traits.hpp>

class C { C() { } };

int main()
{
   static_assert(!boost::has_trivial_default_constructor<C>::value, "Constructible");
   static_assert(!std::is_default_constructible<C>::value, "Constructible");
}

条件不相等,但第一个条件工作正常,第二个构造给出错误,该构造函数是私有的。编译器 gcc 4.7...那么,这是 gcc bug,还是标准定义的?

http://liveworkspace.org/code/NDQyMD http://liveworkspace.org/code/NDQyMD$5

好的。由于这个条件确实不平等 - 我们可以使用这样的东西

#include <type_traits>
#include <boost/type_traits.hpp>

class C { private: C() noexcept(false) { } };

int main()
{
   static_assert(!boost::has_nothrow_constructor<C>::value, "Constructible");
   static_assert(!std::is_nothrow_constructible<C>::value, "Constructible");
}

http://liveworkspace.org/code/NDQyMD http://liveworkspace.org/code/NDQyMD$24

无论如何,我知道 static_assert 不应该失败,因为类型实际上不是默认可构造的/不可抛出构造的。问题是:为什么会出现编译错误,而不是我的静态断言?


看起来像一个编译器错误。让我们看看下面的 SFINAE 示例(类似的实现用于g++'s type_traits header)

#include <type_traits>

class Private
{
    Private()
    {

    }
};

class Delete
{
    Delete() = delete;
};

struct is_default_constructible_impl
{
    template<typename T, typename = decltype(T())>
    static std::true_type test(int);

    template<typename>
    static std::false_type test(...);
};

template <class T>
struct is_default_constructible: decltype(is_default_constructible_impl::test<T>(0))
{

};

int main()
{
    static_assert(is_default_constructible<Private>::value, "Private is not constructible");
    static_assert(is_default_constructible<Delete>::value, "Delete is not constructible");
}

第二个断言按预期工作,我们无法推断Delete类型,因为该类只有一个已删除的构造函数。但是当编译器尝试推断类型时Private(),它给出错误:Private::Private() is private。因此,我们有两个带有私有构造函数的类,但其中一个给出了错误,第二个则没有。我认为这种行为是错误的,但我在标准中找不到确认。

附:所有提供的代码均由 clang 编译,没有任何错误。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

std::is_default_constructible 错误,如果构造函数是私有的 的相关文章

随机推荐