【发布时间】:2018-07-16 13:09:34
【问题描述】:
我完全明白为什么这个不能工作了:
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
};
应该不允许吗?
【问题讨论】:
-
the compiler already knows the 'class hierarchy'是的,但是std::is_base_of不是核心功能,而是库功能,这让事情变得更加复杂。 -
@DeiDei:换句话说,“因为 C++ 是一个又一个巨大的抽象泄漏”? ;)
-
目前 is_base_of 是一个非常普通的类模板。为了实现你的想法,你需要一个特殊的 is_base_of 魔术实现和标准的特殊权限来执行这个魔术。标准已经太大了。我们不想为了边际收益而让它变得更大更复杂。
-
我们不想让它变得更大更复杂 @n.m.请为你自己说话:p 没有什么大魔法 - 只是逻辑 :) 如果一个特性不需要了解类的所有内容,只需要了解它的“类层次结构” - 为什么这样做..
-
欢迎您提出建议。
标签: c++ static-assert incomplete-type