[cfe-dev] c++ templates

Doug Gregor doug.gregor at gmail.com
Mon Nov 17 09:06:12 PST 2008


On Sun, Nov 16, 2008 at 9:28 AM, Andrew Sutton
<andrew.n.sutton at gmail.com> wrote:
> That sounds like a good plan. Do you know of any good references on the
> design and implementation of template engines floating around (besides
> code?). I'm curious to see what other people have done.

Unfortunately, no. I thought Vandevoorde & Josuttis' text had a
discussion of the implementation of templates, but they limit their
discussion to instantiation mechanisms. GNU doesn't really document
their approach, unfortunately, so the only thing you have to look at
is their source code. (They do, however, have a decent representation
of templates).

I've thought about the implementation of templates in Clang a bit, and
although I probably won't be able to dive into the implementation now,
I can probably write up a templates-in-Clang manifesto. Some key
points:

  1) The parser must never, ever be involved in template
instantiation. All instantiation will happen within Sema, as an
AST->AST transformation. We need to design with the idea that we might
eventually de-serialize an AST from disk and then instantiate
templates in it, without ever creating a Parser instance. No token
caching allowed!

  2) The AST for a template must be as close to the AST for a
non-template as possible. We'll re-use the same node kinds in the AST,
the same type-checking routines in Sema, etc. We shouldn't have to
check "are we in a template?" to decide how to type-check in Sema;
rather, we ask the question "is this a type-dependent expression?" or
"is this a dependent type?". There's a principle here: the same code
should get the same error messages regardless of whether it's in a
non-template, non-dependent code in a template definition, or
dependent code in a template instantiation.

  3) The jury's still out on how to handle SFINAE. My dream is to
handle it through exceptions: if we're in a SFINAE context and Diag
gets called with a SFINAE-able error, we throw SFINAE error and back
out whatever work we've done until we hit the top-level substitution.
But I'm expecting to have to argue this one, and I won't do so without
a prototype :)

  - Doug



More information about the cfe-dev mailing list