gpt4 book ai didi

c++ - 为什么不能在类声明(不完整类型)中使用 "is_base_of"?

转载 作者:IT老高 更新时间:2023-10-28 21:42:02 30 4
gpt4 key购买 nike

我完全明白为什么这个不能工作了:

class Base {};
class A;
static_assert(std::is_base_of<Base, A>::value, "");

因为没有关于“类层次结构”的信息,但是...为什么以下不能工作?

class Base {};
class A : public Base {
static_assert(std::is_base_of<Base, A>::value, "");
};
(produce: an undefined class is not allowed as an argument to compiler intrinsic type trait)

类型'A'仍然不完全符合static_assert(根据这个概念的定义)。但是 - 编译器已经知道“类层次结构”并且可以为此提供答案。

当然 - 这个 static_assert 可以移动到析构函数或其他任何东西来解决这个问题,但在某些情况下它无法完成,例如:

class Base {};

template<typename T>
struct type_of {
static_assert(std::is_base_of<Base, T>::value, "T is not derived from Base");
using type = int; //* Some normal type in real use
};

class A : public Base {
public:
type_of<A>::type foo(); // Will not compile
};

应该不允许吗?

最佳答案

一个类定义在右大括号}之后是完整的(即,一个类被认为已定义)。
在您的情况下,当您尝试将 Astd::is_base_of 一起使用时,A 尚未完全定义:

class A : public Base {
// no closing brace for A yet, thus A isn't fully defined here
static_assert(std::is_base_of<Base, A>::value, "");
};

另一方面,std::is_base_of 需要完全定义的类型才能工作。
因此错误。


作为一种解决方法,您可以将断言放在 A 的析构函数中:

class A : public Base {
~A() {
static_assert(std::is_base_of<Base, A>::value, "");
}
};

事实上,一个类类型在其成员函数体中被认为是完全定义的。


here更多细节(强调我的):

A class is considered a completely-defined object type ([basic.types]) (or complete type) at the closing } of the class-specifier. Within the class member-specification, the class is regarded as complete within function bodies, default arguments, noexcept-specifiers, and default member initializers (including such things in nested classes). Otherwise it is regarded as incomplete within its own class member-specification.

关于c++ - 为什么不能在类声明(不完整类型)中使用 "is_base_of"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48643562/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com