Peter Dimov wrote:
You can have
vector
v; and then
v.push_back( Circle(10) ); v.push_back( Ellipse(10, 15) ); v.push_back( Square(11) );
Good example. Yes please. There's another way of implementing this, though; rather than pointing to the object in the heap you can store it in-place by allocating enough space for the largest possible derived subclass: class Base { ... }; class Derived: public Base { ... }; template <typename B> class polymorhpic_value_2 { B base; char enough_space_for_dervided_classes_members[1024]; public: template <typename D> // requires D is same as or derived from B void operator=(const D& d) { B::~B(this); new (this) D(d); } }; polymorphic_value_2<Base> p; Derived d; p = d; That's just a sketch; many details omitted! There are some obvious advantages and disadvantages of each approach and I'm definitely not saying this is better than the pointer-to-heap design. But I mention it for this reason: * If your proposed interface for polymorphic_value could also work for this method of implementation, then it is probably a better interface.
It's unfortunate we have to use -> instead of . but that's what's available.
There have been proposals for operator. ; has this been evaluated to see how it would work with them? Similarly the unified a.b() vs. b(a) syntax proposal. Regards, Phil.