'Self type and collections

If I want to have a Self type in C++, I usually resort to CRTP:

template<class Self> struct Base {
    auto self() -> Self* { return static_cast<Self*>(this); }
};
struct Derived : public Base<Derived> {};

void fn() {
    Derived d;
    Derived *p = d.self();
}

But this won't work if I want a collection of Bases:

std::vector<Base<???>*> bases; // <- No useful `Self` parameter here

Is there a way in C++17/C++20 to get a Self type such that the Base can still be used in containers? I don't want to override self() in every child class and I don't want dynamic_casts.


As a small example where Self types come in handy, consider an ICopy interface.

class ICopy {
public:
  virtual ~ICopy() = default;
  virtual auto copy() const -> Self = 0; // Self is not known to C++, but other languages know it
};


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source