我有一个简单的功能模板:
#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;
}
Run Code Online (Sandbox Code Playgroud)
上面的例子将生成2个函数模板实例,一个用于int,另一个用于long.是否有任何g ++选项可以查看函数模板实例化?
您可以使用该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
Run Code Online (Sandbox Code Playgroud)
我不知道为什么每个副本都有两个副本,一个带有.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
Run Code Online (Sandbox Code Playgroud)
如果不支持该选项,您可以使用它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
Run Code Online (Sandbox Code Playgroud)
所以,你可以看到它分别GetMax用int和实例化long.