CRTP 标准::is_default_constructible 无法按预期工作
CRTP std::is_default_constructible not working as expected
template <class T>
class Base {
static_assert(!std::is_default_constructible<T>::value,
"T must not be default constructible");
};
struct X1 : Base<X1> {};
struct X2 : Base<X2> {
X2() = default;
};
struct X3 : Base<X3> {
X3() {};
};
struct X4 : Base<X4> {
X4() : Base{} {};
};
struct Y1 {};
int main() {
// all compile. They shouldn't
X1 x1; X2 x2; X3 x3; X4 x4;
// all compile. They shouldn't:
Base<X1> bx1; Base<X2> bx2; Base<X3> bx3; Base<X4> bx4;
Base<Y1> by1; // static assert fires. This is the expected behavior
}
类级别的static_assert
不会针对任何X
类触发。但是开始Y
(这不会派生Base
)
如果static_assert
在构造函数内移动,它可以正常工作Base
如果is_default_constructible<T>
源自Base
,那么T
在类级别总是错误的,原因是什么?
艾德酮
当Base<X1>
在 X1
的继承列表中实例化时,X1
是不完整的类型。这意味着在检查类范围static_assert
时,X1
不是默认构造的。
Base
的构造函数仅在使用时实例化,此时X1
现在是一个完整的类型,并且是默认可构造的。这就是为什么static_assert
在构造函数内部触发,但不在类范围内触发的原因。
根据
TartanLlama的回答,当T
X
时,T
在类级别是不完整的。
我想在未定义的行为中添加这个结果T
因为is_default_constructible
必须是完整的类型:
适用于is_default_constructible的 CPP 首选项文档:
T 应为完整类型,(可能符合 cv 标准)无效,或阵列 未知边界。否则,行为是未定义的。
相关文章:
- QSqlquery prepare()和bindvalue()不工作
- 导入库可以跨dll版本工作吗
- 以螺旋方式打印矩阵的程序.(工作不好)
- 对象指针在c++中是如何工作的
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++为线程工作动态地分割例程
- 为什么我的 std::ref 无法按预期工作?
- 布尔比较运算符是如何在C++中工作的
- SampleConsensusPrerejective(ext.RANSAC)是如何真正工作的
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- <<操作员在下面的行中工作
- 有人能解释一下为什么下界是这样工作的吗C++的
- ExtractIconEx:可以工作,但偶尔会崩溃
- C++中的memset函数工作不正常
- 当我在第一个循环中使用"auto"时,它工作正常,但是使用"int"它会给出错误,为什么?
- 链表c++插入,所有情况都已检查,但没有任何工作
- 为什么stream::忽略未按预期工作