Seeing the Instantiated Code of C Templates
In C , it can be beneficial to examine the code generated by the compiler for function or class templates. For instance, consider the following template:
<code class="cpp">template <class T> T add(T a, T b) { return a + b; }</code>
When invoked with a specific type, such as add
Compiler Options to Achieve Visibility
One way to accomplish this is by using the -Xclang -ast-print -fsyntax-only option with Clang. This option instructs the compiler to print the abstract syntax tree (AST) of the instantiated template.
Example Usage
Let's create a test file named test.cpp containing the following code:
<code class="cpp">template <class T> T add(T a, T b) { return a + b; } void tmp() { add<int>(10, 2); }</code>
To see the instantiated code for the int specialization, run the following command:
$ clang++ -Xclang -ast-print -fsyntax-only test.cpp
Clang Output
For Clang version 5.0 or later, the output will look like this:
template <class T> T add(T a, T b) { return a + b; } template<> int add<int>(int a, int b) { return a + b; } void tmp() { add<int>(10, 2); }
This output shows the original template, followed by the specialized add
The above is the detailed content of How to View the Instantiated Code of C Templates?. For more information, please follow other related articles on the PHP Chinese website!