如何确保显式实例化的C++模板仅编译一次?相关疑问咨询
C++模板显式实例化问题解答
代码示例
mytemplate.h
template <typename T> void foo(T* thing, std::string other);
mytemplate.cpp
template <typename T> void foo(T* thing, std::string other) { doStuff(thing); } template void foo<MyType1>(MyType1* thing, std::string other); template void foo<MyType2>(MyType2* thing, std::string other);
main1.cpp
#include "mytemplate.h" // 其他代码 foo<MyType1>(thing1, other1); foo<MyType2>(thing2, other2); // 其他代码
main2.cpp
#include "mytemplate.h" // 其他代码 foo<MyType1>(thing, other); // 其他代码
问题解答
1. 该实现是否会让显式实例化的模板仅编译一次?
是的。模板函数的完整定义仅存在于mytemplate.cpp中,其他源文件只有模板声明。编译mytemplate.cpp时,显式实例化的foo<MyType1>和foo<MyType2>会被编译为具体的机器码,生成对应的目标文件。而main1.cpp、main2.cpp在编译阶段只会生成调用这些函数的指令,不会重复实例化编译模板。整个项目中这两个模板实例只会被编译一次,链接阶段直接复用mytemplate.cpp生成的目标文件中的函数实现。
2. 代码其他位置能否用不同模板参数隐式实例化该模板?
不能。其他源文件仅能看到模板的声明,没有访问到模板的定义。如果在某个源文件中尝试调用foo<MyType3>(...)这类未显式实例化的版本,编译器在编译该源文件时无法获取模板定义来完成隐式实例化,最终会触发链接错误(提示找不到foo<MyType3>的函数定义)。只有在mytemplate.cpp中显式实例化的模板参数版本才会被编译生成可调用的函数。
内容的提问来源于stack exchange,提问作者monkey_brain_444
相关产品推荐
相关产品推荐

