如何复现并查看C++中的冗余模板实例?
如何复现并查看C++模板的冗余实例化
背景
我正在学习C++的模板实例化流程——显式实例化声明与定义。查阅资料得知,显式实例化声明可以避免编译时出现冗余模板实例化,现在想知道具体怎么复现这种冗余实例的行为,并且找到它们进行查看。
我尝试了以下代码,分别添加和不添加extern template声明,之后反编译.obj文件,但没找到ATest被多次实例化的痕迹,可能是我对反编译代码理解不足,甚至不确定找没找对位置。
测试代码
TestA.h
template <typename T, T val> struct ATest { ATest(); T foo(); T bar(); }; //extern template struct ATest<int, 55>; //extern template ATest<int, 55>::ATest(void); //extern template int ATest<int, 55>::foo(void); //extern template int ATest<int, 55>::bar(void);
TestA.cpp
#include <iostream> #include "TestA.h" template <class T, T val> T ATest<T, val>::foo(void) { std::cout << "Hello from foo" << std::endl; return val; } template <class T, T val> T ATest<T, val>::bar(void) { std::cout << "Hello from bar" << std::endl; return val; } template <class T, T val> ATest<T, val>::ATest(void) { std::cout << "Hello from A()" << std::endl; } template struct ATest<int, 55>; template ATest<int, 55>::ATest(void); template int ATest<int, 55>::foo(void); template int ATest<int, 55>::bar(void);
MainA.cpp
#include "TestA.h" int main() { ATest<int, 55> a; ATest<int, 55> b; ATest<int, 55> c; ATest<int, 55> d; ATest<int, 55> e; ATest<int, 55> f; ATest<int, 55> g; return 0; }
相关更新
- 更新1:我的问题被关联到《为何模板只能在头文件中实现?》一文,但这和我的问题无关——我不是在问模板在头文件的使用方式,而是关注模板实例化的编译结果。目前我C++经验尚浅,若表述有混淆请见谅。
- 更新2:另一关联文章《使用extern template (C++11)》讲了很多示例,但没说明要反编译哪些内容、怎么看差异,也没解决我的问题。
- 更新3(我的解决方案):通过阅读《显式模板实例化——何时使用?》一文,我摸索出了生成冗余实例的方法:要同时跳过显式实例化的声明和定义,并且把模板定义放在头文件中。不过我对冗余实例化的概念还没完全理解。
内容的提问来源于stack exchange,提问作者Dron4K
相关产品推荐
相关产品推荐

