Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to expand/"preprocess" C++ template code

To properly debug complex macros in C++ I usually run the preprocessor on them in order to see exactly what the resulting code looks like.

Is there a similar way to "preprocess" template code?

like image 623
sharkin Avatar asked Mar 04 '11 12:03

sharkin


3 Answers

One way (compiler-dependent) is to use dumping after each compiler step. I wrote a small program:

template<class T>
T square(T n)
{
    return n * n;
}

int main(void)
{
    square<int>(3);
    square<float>(3.0);
}

then:

g++ -fdump-rtl-all test.cc

This get me a bunch of files. Take a look at (in my case) test.cc.218.dfinish:

;; Function int main() (main)
;; Function T square(T) [with T = int] (_Z6squareIiET_S0_)
;; Function T square(T) [with T = float] (_Z6squareIfET_S0_)
like image 198
maverik Avatar answered Oct 19 '22 21:10

maverik


The CLang compiler features an option -emit-ast which dumps the Abstract Syntax Tree used to represent the parsed language. The various instantiations of the template will be represented.

The AST is represented both in memory and in xml version, so you can:

  • just use the XML output
  • parse it, then produce some C++ code
  • create a Rewriter tool (supported directly in CLang) and consume the AST itself

For most code inspections (including checking the overloads selected) I have found that actually reading the XML output (well, grepping through it) was sufficient for my needs.

like image 43
Matthieu M. Avatar answered Oct 19 '22 20:10

Matthieu M.


This is a fairly old question, but I think there has been significant improvements in this area that are not so widely known (yet).

Metashell can be used like a sort of gdb for template instantiations. This (as far as I know) builds on clang tooling.

enter image description here

like image 2
Tamás Szelei Avatar answered Oct 19 '22 21:10

Tamás Szelei