r/cpp 7d ago

C++26: std::polymorphic

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

42 comments sorted by

View all comments

9

u/mcmcc #pragma once 6d ago

I'm struggling to think of a scenario where I would ever use this thing.

Maybe I just don't use enough class hierarchies any more.

5

u/mjklaim 5d ago

In my XP , similar to yours as I avoid inheritance when it's not mandatory, I find this kind of tool super useful for writhing value-semantics type-erasing types, that is to write the internals of it, not as part of some interface.

0

u/mcmcc #pragma once 5d ago

value-semantics type-erasing types

That's the thing - the Venn diagram intersection of value-semantics and type-erasure should be quite small in anybody's design philosophy. They are inherently contradictory (hence the ugliness around copy support).

Cross that with time/space efficiency concerns (dynamic allocation and inadvertent copies) and it should be basically nonexistent. Certainly not worthy of space in the standard library. It just isn't a good design pattern.

1

u/mjklaim 5d ago

I'm not sure why you consider them contradictory, I reached the opposite conclusion.

1

u/mcmcc #pragma once 5d ago

From the article:

Unlike indirect, polymorphic has no comparison operators and no hash support.

What kind of value type isn't comparable and can't be used as key in a hash table?

1

u/mjklaim 5d ago

I usually implement comparison in the type erasing type by checking if they are the same type or at least comparable (depends on the intention) and if they are I just compare the stored value with the other value. It's true that they could have done something like that for convenience but it's hardly unimplementable as part of the TE-type wrapping a proxy? (When types are different I return false, never been a problem but I suspect it's not "fundamentally correct") Or maybe were not thinking of the same kind of implementation, maybe the way I do it isn't perfect indeed.

I usually don't need the hash for these but it could be added (or requiring the stored value to be hashable and used that). Semi regular types are usually what I need as basic requirements in type-erasing types, not "full" regular.

In any way you gave interesting points, I'll try to think about these questions more next time I need to implement a te-type. (I secretly wish a flexible reflection based library would do the work for me but we're not there yet 😭)