Hacker News new | ask | show | jobs
by joe_the_user 3926 days ago
Amazingly, there is no easy way to define a type in C++ which can be "one of these or one of these", e.g. a sphere or a group in this case.

The author may have assumptions I'm missing here but the standard way to have a "one of these or one of these" thing is to have two classes inherent from a given abstract base class and use a pointer to the base class.

If one wants the device specifically as a type, one could wrap the base-pointer in a class.

Is there something I'm missing?

2 comments

https://programmers.stackexchange.com/questions/231092/is-pa... points out some differences.

Some of the things that make me miss OCaml variants/sum types when I have to use C++ subclassing/dynamic dispatch instead: * very lightweight syntax both for creating them and matching on them (and lightweight representation; variants without arguments are just ints under the hood) * compile-time checks on exhaustiveness in pattern matches (so no unexpected NULL's!)

Note that OCaml also allows open/polymorphic variants for the cases where you want to allow expanding the list of options – here the compiler will only check that e.g. a function that matches on only `A|`B won't be sent a `C, although it can be sent a member of a type that contains only `A's. This is typically used for public interfaces where you want to let your implementation expand later (e.g. your current function accepts `UTF8|`UTF16 but you might later decide to accept `WTF8 as well).

> The author may have assumptions I'm missing here but the standard way to have a "one of these or one of these" thing is to have two classes inherent from a given abstract base class and use a pointer to the base class.

I think this is what the author describes in the sentence that follows the one you quoted. He also calls it "a common (ab)use of object oriented programming."

So it's reasonable to define data types in this way in OCaml, but it's abusing OO to do so in C++? Given that classes are data types, that seems... less than consistent.