为什么要检查 Base 是 Derived 的私有还是受保护的基数?

Why should you check if Base is a private or protected base of Derived?

std::is_base_of<Base, Derived>std::is_convertible<Derived*, const volatile Base*> 之间的唯一区别是前者在 Baseprivate 或 protected 基 class 共 Derived。但是,您什么时候真正需要知道 Base 是私人基地还是受保护基地?用户为什么要关心 class 的内部实现?

举个例子,考虑

template <typename T>
struct Foo : T, Bar {};

在这种情况下,即使继承受到保护,T 是否继承自 Bar(或任何其他 class)也不再是实现细节。

对于私有继承,考虑一个基 class 做一些簿记。例如,每次创建实例时都创建日志条目。现在,当我从第二种类型继承时,如 template <typename T> struct Foo : T {}; 我想知道 T 是否已经从簿记 class 继承,或者我是否必须自己添加它。

你的假设是错误的。

  1. std::is_convertible 涵盖的用例比 std::is_base_of.

    多得多

    它也适用于用户定义的转换运算符以及 基元。

    https://gcc.godbolt.org/z/JULbVf

  2. 如果 class 私下继承了一个 Base class,这不是内部实现细节,但对 [=29= 的 public 接口有影响].例如,无法转换为基数 class。

以下class:

class C
{
    operator int() { return 0; }
};

可转换为整数:

constexpr bool is_int = std::is_convertible_v<C, int>; // true

但 int 不是 C:

的基数
constexpr bool is_base = std::is_base_of_v<int, C>; // false

所以你的前提是,这些功能存在的唯一原因是:

But, when do you really need to know if Base is a private or protected base? Why should the user care about internal implementation of a class?

不正确。还有其他用例。