![](/img/trans.png)
[英]Can we assume std::is_default_constructible<T> and std::is_constructible<T> to be equal?
[英]std::is_default_constructible<T> error, if constructor is private
我有以下片段
#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错误,还是由标准定义的?
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 $ 24
无论如何,我知道,static_assert不应失败,因为类型实际上不是默认可构造的/不可构造的。 问题是:为什么会有编译错误,不是由我的静态断言引起的?
看起来像一个编译器错误。 让我们看一下SFINAE的以下示例(在g++
的type_traits
标头中使用了类似的实现)
#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");
}
第二个assert可以按预期工作,我们不能推断Delete
类型,因为该类只有一个已删除的构造函数。 但是,当编译器尝试推断Private()
类型时,会出现错误: Private::Private() is private
。 因此,我们有两个带有私有构造函数的类,但是其中一个给出了错误,第二个给出了错误。 我认为这种行为是错误的,但是我在标准中找不到确认。
PS全部提供的代码均由clang编译,没有任何错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.