在前向声明类层次结构的shared_ptr之间进行强制转换

Casting between shared_ptr of forward declared class hierarchy

本文关键字:之间 ptr 转换 shared 声明 层次结构      更新时间:2023-10-16

我有一个类只操作shared_ptr到继承层次结构(相当简单,有几个类,说A, B, C等从单个类Base继承)。因为我不需要操作A, B, C…它们本身只是向前宣布的。然而,当我试图将shared_ptr<A>传递给采用shared_ptr<Base>的方法时,编译器会阻塞,因为编译器不知道a继承自Base。除了static_pointer_cast#include之外,还有其他方法可以作为A类的头吗?如果没有,你会选择哪一个?

编辑:添加一些代码

// in some file: (Base.h)
class Base
{
    /*code*/
}
// in another file (A.h)
class A : public Base
{
}
// in my file (impl.cpp)
class A; // forward declaration    
void Dummy()
{
    std::shared_ptr<A> myPtr;
    // we have somewhere: void sillyFunction(shared_ptr<Base> foo)
    sillyFunction(myPtr); // does not compile, as no conversion is found.
}

除了static_pointer_castor #包含类A的头文件之外,还有其他方法吗?

。事实上,#include是正确执行此操作的唯一方法(static_pointer_cast要么不起作用,要么调用未定义的行为)。也不能在不完整子类和超类之间强制转换普通指针