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.
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.
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!
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.
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.
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); }
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With