如果我将基类的this指针强制转换为派生类型,那么它是安全的还是很好的定义?

时间:2017-08-09 19:46:44

标签: c++ crtp

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

考虑这段代码,基类A将this指针强制转换为模板参数(Derived)。它还检查提供的类型是否实际来自此类。它显然有效(这里),但它定义得很好吗?

#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();
}

1 个答案:

答案 0 :(得分:2)

  

如果我有一个采用派生类类型的模板基类,可以安全地将此基类的this指针强制转换为派生类的类型吗?   ...
  它显然有效(这里),但它定义得很好吗?

是的,这是安全的并且定义明确。它实际上是一个众所周知且常用的模式(参见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
}
相关问题