我完全明白为什么会这样cannot work:
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
};
难道不应该被允许吗?
类定义已完成(即类被认为是已定义的) 在右大括号之后}
.
在你的情况下,当你尝试使用A
with std::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, "");
}
};
事实上,类类型被认为是在其成员函数体内完全定义的。
See here http://eel.is/c++draft/class#mem-6有关更多详细信息(强调我的):
在类说明符的结尾 } 处,类被视为完全定义的对象类型 ([basic.types])(或完整类型)。在类成员规范中,类在函数体内被认为是完整的、默认参数、noexcept 说明符和默认成员初始值设定项(包括嵌套类中的此类内容)。否则,它在其自己的类成员规范中被视为不完整。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)