Wednesday, February 7, 2007

C++ and GADTs

I just noticed this post about GADTs in C++. It's more about C++'s warts than GADTs, but it's interesting nonetheless.

I also noticed recently, while preparing for my upcoming talk at the theory lunch (mirror, suspected future permalink, presently 404), that because the constructors in the OOP version of GADTs each get their own class, the class name can function as the constructor tag. This leads to what is called the Curiously Recurring Template Pattern in C++. Example:

Haskell C++
data Nat t where
    Z :: Nat ZTag
    S :: Nat n -> Nat (STag n)
data ZTag
data STag n
template<class T>
class nat {};

class zero : nat<zero> {};

template<class N>
class succ : nat<succ<N> > {
public:
  succ<N>(nat<N> x) : pred(x) {}
  nat<N> pred;
};

Of course, the tags in the Haskell version could have the same names as the constructors, since the constructor and type namespaces in Haskell are disjoint, but they would still have distinct meanings, unlike in the C++ code.

1 comment:

sigfpe said...

So now I can port this to Haskell. And there I was thinking that by learning Haskell I could give up that kind of compiler abuse...