Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we see the template instantiated code by C++ compiler

Tags:

c++

is there a way to know the compiler instantiated code for a template function or a class in C++

Assume I have the following piece of code

template < class T> T add(T a, T b){             return a+b; } 

now when i call

add<int>(10,2);  

I would like to know the function that compiler creates for int specific version.

I am using G++, VC++. It will be helpful if some can help me point out the compiler options to achieve this.

Hope the question is clear. Thanks in advance.

like image 932
Vineel Kumar Reddy Avatar asked Dec 15 '10 08:12

Vineel Kumar Reddy


People also ask

What is created when the template is instantiated?

The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation to handle a specific set of template arguments is called a specialization.

Are templates resolved at compile-time?

All the template parameters are fixed+known at compile-time. If there are compiler errors due to template instantiation, they must be caught at compile-time!

How templates are compiled?

Template compilation requires the C++ compiler to do more than traditional UNIX compilers have done. The C++ compiler must generate object code for template instances on an as-needed basis. It might share template instances among separate compilations using a template repository.

What is the role of compiler by templates?

Compiler creates a new instance of a template function for every data type. So compiler creates two functions in the above example, one for int and other for double. Every instance has its own copy of static variable. The int instance of function is called twice, so count is incremented for the second call.


2 Answers

Clang (https://clang.llvm.org/) can pretty-print AST of instantiated template:

For your example:

test.cpp

template < class T> T add(T a, T b){     return a+b; }  void tmp() {     add<int>(10,2);  } 

Command to pretty-print AST:

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

Clang-5.0 output:

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); } 
like image 159
random Avatar answered Oct 08 '22 07:10

random


If you want to see the assembly output, use this:

g++ -S file.cpp 

If you want to see some (pseudo) C++ code that GCC generates, you can use this:

g++ -fdump-tree-original file.cpp 

For your add function, this will output something like

;; Function T add(const T&, const T&) [with T = int] (null) ;; enabled by -tree-original  return <retval> = (int) *l + (int) *r; 

(I passed the parameters by reference to make the output a little more interesting)

like image 42
mtvec Avatar answered Oct 08 '22 05:10

mtvec