[cfe-dev] Source-to-source template resolution

John McCall rjmccall at apple.com
Wed Jun 19 10:41:20 PDT 2013


On Jun 19, 2013, at 5:53 AM, Leszek Świrski <leszek at swirski.co.uk> wrote:
> 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
> 
>     template<class T>
>     struct A {
>         T val;
>     };
> 
>     A<int> x;
>     A<double> y;
> 
> into
> 
>     struct A_int {
>         int val;
>     };
>     struct A_double {
>         double val;
>     };
> 
>     A_int x;
>     A_double y;

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.

John.



More information about the cfe-dev mailing list