Source-to-source template resolution

I’m not sure if this is the right mailing list for this sort of question, but I couldn’t think of a better one. Would it be possible to parse a C++ file using clang, and perform a source-to-source transformation replacing all templates with resolved instances of that template? Something like transforming

struct A {
T val;

A x;
A y;


struct A_int {
int val;
struct A_double {
double val;

A_int x;
A_double y;

  • Leszek

Yes; templates keep track of their instantiations. However, there is no guarantee that a naive expansion at the point of definition of the template will actually compile, because it is not uncommon for a template to use functions and types that are not declared or defined until later in the translation unit.

You could, of course, forward-declare all the instantiations at the point of the first declaration of the template and then define them later, but deciding the correct location to define an instantiation is non-trivial (when it is even possible — it's not always).

You will also frequently need to take member functions and define them out-of-line instead of inline. Again, the lookup rules make it not always possible to find a location to put these functions that does not change the semantics of the program.