Algebraic data types: Difference between revisions

Content added Content deleted
(Corrected C++ language tags)
Line 100: Line 100:
C++ templates have a robust pattern matching facility, with some warts - for example, nested templates cannot be fully specialized, so we must use a dummy template parameter. This implementation uses C++17 deduced template parameters for genericity.
C++ templates have a robust pattern matching facility, with some warts - for example, nested templates cannot be fully specialized, so we must use a dummy template parameter. This implementation uses C++17 deduced template parameters for genericity.


<lang c++>enum Color { R, B };
<lang cpp>enum Color { R, B };
template<Color, class, auto, class> struct T;
template<Color, class, auto, class> struct T;
struct E;
struct E;
Line 149: Line 149:
Although C++ has structured bindings and pattern matching through function overloading, it is not yet possible to use them together so we must match the structure of the tree being rebalanced separately from decomposing it into its elements. A further issue is that function overloads are not ordered, so to avoid ambiguity we must explicitly reject any (ill-formed) trees that would match more than one case during rebalance.
Although C++ has structured bindings and pattern matching through function overloading, it is not yet possible to use them together so we must match the structure of the tree being rebalanced separately from decomposing it into its elements. A further issue is that function overloads are not ordered, so to avoid ambiguity we must explicitly reject any (ill-formed) trees that would match more than one case during rebalance.


<lang c++>#include <memory>
<lang cpp>#include <memory>
#include <variant>
#include <variant>