我可以在不知道类型参数的情况下持有 shared_ptr 吗?

Can I hold a shared_ptr without knowing the type parameter?

我想持有一个shared_ptr的模板class。但是,我也不想将 class B 作为模板 class。在我看来,任何类型的 shared_ptr 都将具有相同的内存布局。所以我想知道在这种情况下有什么解决方法吗?

template<T>
class A {
...
};

class B {
...
  std::shared_ptr<A<T>> ptr;
}

当类型完全不重要时,可以使用void

template <typename>
class C {};

std::shared_ptr<void> p = std::make_shared<C<int>>();

添加单态基 class 允许限制可以存储的类型。

class AnyC {};

template <typename>
class C : public AnyC {};

std::shared_ptr<AnyC> p = std::make_shared<C<int>>();

如果该基 class 具有虚方法,则可以通过指针调用它们。

class AnyC {
    virtual void f();
};

template <typename>
class C : public AnyC {
    void f() override;
};

std::shared_ptr<AnyC> p = std::make_shared<C<int>>();
p->f();