Building off of ecatmur's answer, we could also make Base
constructible from a type that only has a private constructor:
class PrivateT {
PrivateT() { }
template <typename Impl, typename... Args>
friend std::shared_ptr<Impl> makeDerived(Args&&... );
};
struct Base : std::enable_shared_from_this<Base> {
Base(PrivateT ) { }
virtual void foo() = 0;
void bar() {
baz(shared_from_this());
}
};
template <typename Impl, typename... Args>
std::shared_ptr<Impl> makeDerived(Args&&... args) {
return std::make_shared<Impl>(std::forward<Args>(args)...,
PrivateT{});
}
Every Derived
type will have to take an extra constructor argument of type PrivateT
that it will have to forward through... but it will still be able to inherit from Base
!
struct Impl : Base {
Impl(PrivateT pt) : Base(pt) { }
void foo() override { std::cout << "Hello!" << std::endl; }
};
auto gd = makeDerived<Impl>();
gd->bar();