View function template instances

I have a simple function template:

#include <iostream> using namespace std; template <class T> T GetMax (T a, T b) { T result; result = (a > b) ? a : b; return (result); } int main () { cout << GetMax<int>(5, 6) << endl; cout << GetMax<long>(10, 5) << endl; return 0; } 

In the above example, 2 instances of the function template will be created, one for int and the other for long ones. Is there a g ++ option to view instances of function templates?

+4
source share
2 answers

You can use the nm program (part of binutils ) to view a list of characters used by your program. For instance:

 $ g++ test.cc -o test $ nm test | grep GetMax 00002ef0 T __Z6GetMaxIiET_S0_S0_ 00002f5c T __Z6GetMaxIiET_S0_S0_.eh 00002f17 T __Z6GetMaxIlET_S0_S0_ 00002f80 T __Z6GetMaxIlET_S0_S0_.eh 

I don’t know why each of them has two copies, one with the suffix .eh , but otherwise you can say that this particular function was created twice. If the nm version supports the -C/--demangle , you can use this to get readable names:

 $ nm --demangle test | grep GetMax 00002ef0 T int GetMax<int>(int, int) 00002f5c T _Z6GetMaxIiET_S0_S0_.eh 00002f17 T long GetMax<long>(long, long) 00002f80 T _Z6GetMaxIlET_S0_S0_.eh 

If this option is not supported, you can use c++filt to untie them:

 $ nm test | grep GetMax | c++filt 00002ef0 T int GetMax<int>(int, int) 00002f5c T __Z6GetMaxIiET_S0_S0_.eh 00002f17 T long GetMax<long>(long, long) 00002f80 T __Z6GetMaxIlET_S0_S0_.eh 

So you can see that GetMax was created using int and long respectively.

+5
source

If you have a linker, create a map file, you can see the names of all the generated symbols. Some parsing with grep / perl may give you what you want. Names will be distorted.

This command line worked for me:

 g++ -o test -Wl,-map,test.map test.cpp 

test.map will be generated.

It may be further down the line than you are looking for.

+1
source

All Articles