为什么我的衍生自CRTP函数工作

Why does my derived from CRTP function work?

本文关键字:CRTP 函数 工作 我的 为什么      更新时间:2023-10-16

我正在尝试编写一个函数,检查类是否从基类派生。基类遵循奇怪的递归模板模式,也就是说,它是这样定义的:

template<class Derived>
class Base{

派生类是这样派生的:

class Derived: Base<Derived>{

检查一个类是否以这种方式派生,我写了这个检查器:

template<class T>
constexpr bool basedOn(){
    return std::is_base_of<Base<T>,T>::value;
}

它成功了!我很惊讶。除非直接从Base派生,否则似乎没有任何东西返回true。为什么它会起作用?使用CRTP派生的类的完整类型是什么?

Derived的完整类型就是Derived。但是它确实继承了类型Base<Derived>,就像您定义它一样。