查看功能模板实例化

时间:2010-01-04 01:41:22

标签: c++ templates g++

我有一个简单的功能模板:

#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;
}

上面的示例将生成2个函数模板实例化,一个用于 int ,另一个用于 long 。是否有任何g ++选项可以查看函数模板实例化?

2 个答案:

答案 0 :(得分:5)

您可以使用nm程序(binutils的一部分)查看程序使用的符号列表。例如:

$ 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

我不知道为什么每个人都有两个副本,一个带有.eh后缀,但是你可以告诉我这个特定的功能被实例化了两次。如果nm版本支持-C/--demangle标志,则可以使用它来获取可读名称:

$ 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

如果不支持该选项,您可以使用c++filt对其进行解码:

$ 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

因此,您可以看到GetMax分别使用intlong进行了实例化。

答案 1 :(得分:1)

如果链接器生成了映射文件,则可以看到所有生成的符号的名称。一些使用grep / perl解析可能会得到你想要的。这些名字将被破坏。

这个命令行对我有用:

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

将生成test.map。

这可能比你想要的更进一步。