Home > Backend Development > C++ > body text

How to View the Instantiated Code of C Templates?

Linda Hamilton
Release: 2024-10-27 15:53:29
Original
148 people have browsed it

How to View the Instantiated Code of C   Templates?

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>
Copy after login

When invoked with a specific type, such as add(10, 2), we may want to view the function that the compiler creates for this particular specialization.

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>
Copy after login

To see the instantiated code for the int specialization, run the following command:

$ clang++ -Xclang -ast-print -fsyntax-only test.cpp
Copy after login

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);
}
Copy after login

This output shows the original template, followed by the specialized add function that the compiler has instantiated.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!