std::is_base_of 在 C++ 11 中的逻辑

Logic of std::is_base_of in C++ 11

本文关键字:is base of std C++      更新时间:2023-10-16

在浏览一些C++概念时,我偶然发现了std::is_base_of逻辑。

谷歌搜索逻辑产生了下面的代码,但我无法理解它。

有人可以解释一下它是如何工作的吗?

template<typename D, typename B>
class IsDerivedFromHelper
{
    class No { };
    class Yes { No no[3]; };
    static Yes Test( B* );
    static No Test( ... );
public:
    enum { Is = sizeof(Test(static_cast<D*>(0))) == sizeof(Yes) };
};

template <class C, class P> 
bool IsDerivedFrom() {
    return IsDerivedFromHelper<C, P>::Is;
}

BD的基类时,调用Test(static_cast<D*>(0))解析为Yes Test(B*)。否则,它将解析为 No Test(...)

如果 BD 的基类,则 sizeof(Test(static_cast<D*>(0))) 的值为 sizeof(Yes) 。否则,它等于 sizeof(No) .

YesNo的定义使得sizeof(Yes)永远不会等于sizeof(No)

如果BD的基类,

sizeof(Test(static_cast<D*>(0))) == sizeof(Yes)

评估为 true .否则,它的计算结果为 false

相关文章: