Can I hold a shared_ptr without knowing the type parameter?

Viewed 377

I would like to hold a shared_ptr of a template class. However, I don't want to make the class B as a template class too. In my understanding, shared_ptr with any type will have the same memory layout. So I am wondering any workaround in this scenario?

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

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

When the type doesn't matter at all, void can be used.

template <typename>
class C {};

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

Adding a monomorphic base class allows restricting the type that can be stored.

class AnyC {};

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

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

If that base class has virtual methods they can be called through the pointer.

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();
Related