r/Compilers • • Jul 13 '26

Delayed Specialization: A Third Way to Implement Generics?

While implementing generics in my GCC-based language (AET), I wasn't satisfied with the two mainstream approaches:

  • C++ Templates: Generate a full copy of the code for every concrete type (monomorphization) → code bloat and longer compile times.
  • Java Generics: Use type erasure → no code duplication, but lose concrete type information.

So I explored a middle path: Delayed Specialization.

How it works in AET:

During the first compilation:

  • Generic parameters (E, T, ...) are treated as void*
  • Code that needs the real type is wrapped in a genericblock$

For example:

class$ Abc<E>{
  void setData(E value);
};

impl$ Abc{
   void setData(E value) {
      E a = value;
      genericblock$(a) {
        E x = a;
        E y = 5;
        x += y;
      }
   }
};

When the compiler later sees a concrete instantiation like Abc<int>, it performs a second compilation pass only on the Generic Blocks, replacing E with int.

Benefits:

  • Avoids C++-style template explosion
  • Keeps most generic code shared (like Java)
  • Still allows real type-specific operations where needed

I call this Delayed Specialization. It sits between full monomorphization and type erasure.

Has anyone seen a similar approach in other languages or compilers? I'd love to hear about papers or existing implementations using delayed/late specialization.

31 Upvotes

42 comments sorted by

View all comments

Show parent comment

6

u/munificent Jul 13 '26

The generic parts can be shared, while type-dependent parts are handled during specialization.

In practice, how often do you find that to lead to a noticeable amount of savings? I would expect that most code inside a generic function would either:

  • Not depend on the type argument at all in which case there's no need to specialize anything. In your model, I think that would mean you'd end up with no generic blocks in it. Basically, the kinds of code that work fine in Java or SML.
  • Depend on the type argument such that basically everything in the function gets slurped into the generic block.

Do you really find a lot of savings where you have functions that do have generic blocks but where much of the code is outside of them?