Sum types in ALFE

This is part of the ALFE types series.

Foo | Bar is a "sum" type, in other words a type that can have any values that Foo can as well as any values that Bar can. Also known as a tagged union or an algebraic data type.

Foo | Bar acts like a base class (supertype) of both Foo and Bar, since either of the latter are Liskov-substitutable for the former, and the downcast required to convert from the former to the latter is identical that required for casting from a base class. Foo | Baz also acts like a (completely separate) base class of Foo, so sum types provide something almost, but not quite, entirely unlike multiple inheritance.

Foo | Bar has all the methods and members of the most derived common base class of Foo and Bar (and, if that common base class has no other subclasses not derived from Foo or Bar, it'll be identical to Foo | Bar. In particular, Foo | Foo is identical to Foo).

Foo | Bar is syntactic sugar for a special template Either<Foo, Bar>. Similarly, Foo | Bar | Baz is syntactic sugar for Either<Foo, Bar, Baz> - Either is a variadic template. Either<Foo> is just another name for Foo.

How Either is actually implemented is up to the compiler, but some kind of boxing will probably be necessary in the case when Foo and Bar are not both pointers to types with vtable pointers.

One Response to “Sum types in ALFE”

  1. […] of the types in ALFE are templates which can accept different numbers of parameters - in other words, […]

Leave a Reply for Variadic templates in ALFE « Reenigne blog