r/cpp 13d ago

C++26: std::polymorphic

https://www.sandordargo.com/blog/2026/08/19/cpp26-polymorphic
98 Upvotes

44 comments sorted by

View all comments

6

u/Ok_Independence_9841 13d ago edited 13d ago

I've read your blog post and I've been looking at the prototype implementation, which is C++20 so I could use it directly. What I don't see is how this can handle multiple inheritance and yet I can find no mention anywhere that it doesn't?
The somewhat odd, partial, type erasure that's going on definitely avoids slicing and uses derived copy constructors to implement clone for you, which is nice but I'm not convinced this is going to cope with multiple virtual bases. I also see nothing that prevents it trying to allocate/construct abstract bases which will clearly blow up but isn't caught explicitly as far as I can see. I'm still studying the source so any and all my conclusions may be wrong. Trying to determine if this is what I hoped it was.
...
OK I think I get it. std::polymorphic as it stands is fine as long as you always want to treat it as the base class. Virtual function calls will work of course but what you can't do here is get back a pointer to the derived instance you actually stored. So if those pointers are not the same address, as they won't be in the case of multiple inheritance, you're stuffed. A dynamic downcast might work or it might not depending on the compiler. Ick.
It's still a cool addition to the standard library and does what it sets out to do, just not quite what I need.

3

u/LB-- Professional+Hobbyist 13d ago

Do you have any examples of class inheritance hierarchies where you're worried it won't work?

2

u/Ok_Independence_9841 12d ago

I do, embedded in a lot of other code, but I must be wrong about it trying to construct abstract bases. I'll post if/when I get any real world issues. I realised that what I was expecting this to need (it doesn't) must live in std::dynamic_pointer_cast so I had a look at Microsoft's source code for that. Literally just a dyamic_cast. What I'm already doing. So if I have a problem then Microsoft stdlib will too. More research needed.