如果我将基 class 的 this 指针转换为派生类型,它是否安全且定义良好?

If I cast the this pointer of a base class to the derived type, is it safe and well defind?

如果我有一个采用派生类型 class 的模板基 class,可以安全地将此基 class 的 this 指针转换为派生类型class?

考虑这段代码,其中基 class A 将 this 指针转换为模板参数 (Derived)。它还会检查提供的类型是否真的派生自此 class。它显然有效(在这里),但它定义明确吗?

#include <iostream>

class D;

template<typename Derived, typename T>
class A
{
public:
    Derived *thisToDerived() {
        static_assert(std::is_base_of< A<Derived, T>, Derived>::value, "not");
        return static_cast<Derived*>(this);
    }
private:
    T m;
};


class D : public A<D, int>
{
private:
    double d;
    float f;
};


int main() {
    D d;
    std::cout<<"this:    "<<&d<<"\nderived: "<<d.thisToDerived();
}

If I have a template base class that takes the type of the derived class, is safe to cast the this pointer of this base class to the type of the derived class?
...
It obviously works (here), but is it well defined?

是的,它安全且定义明确。它实际上是一个众所周知且常用的模式(参见 CRTP),又名 静态多态性.

使用示例:


Derived *thisToDerived() {
    // Your static_assert is superfluos
    // static_assert(std::is_base_of< A<Derived, T>, Derived>::value, "not");
    return static_cast<Derived*>(this);
        // ^^^^^^^^^^^^^^^^^^^^^
        // Already guarantees that Derived is inherited from A
}