std::is_base_of 在 C++ 11 中的逻辑
Logic of std::is_base_of in C++ 11
在浏览一些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;
}
当B
是D
的基类时,调用Test(static_cast<D*>(0))
解析为Yes Test(B*)
。否则,它将解析为 No Test(...)
。
如果 B
是 D
的基类,则 sizeof(Test(static_cast<D*>(0)))
的值为 sizeof(Yes)
。否则,它等于 sizeof(No)
.
Yes
和No
的定义使得sizeof(Yes)
永远不会等于sizeof(No)
。
如果B
是D
的基类,
sizeof(Test(static_cast<D*>(0))) == sizeof(Yes)
评估为 true
.否则,它的计算结果为 false
。
相关文章:
- C++核心准则 C35 对于接口类"A base class destructor should be either public and virtual, or protected and nonv
- Why is UINT32_MAX + 1 = 0?
- C++错误:"error: int aaa::bbb is protected within this context"
- 构造函数采用 Base&不被调用
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 使用 cmake 的 Linux 终端上的"Conversion to non-scalar type is requested"错误
- 将sharet_ptr<Derived>转换为shared_ptr<Base>
- 尝试应用肖恩父母谈话"inheritance is the base class of evil"中的模式
- C++中的继承,"...is an ambiguous base of ..."错误
- 为什么在使用dynamic_cast和模板时出现错误"A is an inaccessible base of B"?
- what is Base*(*)()
- 不断收到错误"member reference base type 'string [1000]' is not a structure or union"不知道如何解决?
- C++错误,显示创建链接列表调用"error LinkedList Interface is an inaccessable base of linkedlist"
- 子构造函数无法识别基类的成员:平均值,西格玛"is not a nonstatic data member or base class"
- 为什么这段代码会出现"exception spec is more lax than base"错误?
- 如何在C++实现继承并解决错误"parent class is not accessible base of child class"?
- 关于肖恩·帕伦特谈话的澄清 "Inheritance is the base class of evil"
- 实现观察者模式的问题:"Member reference base type ________ is not a structure or union"
- 我怎么能说"noexcept if execution of protected base constructor is noexcept"?
- "Is not a direct base of " GCC 4.5.2 编译器错误