【发布时间】:2014-03-22 09:40:02
【问题描述】:
(不再那么新的)C++11 标准为模板引入了extern 关键字。其目的是告诉编译器不应在使用时实例化模板,而是将在另一个翻译单元中实例化它(因此在链接时会有一个可用的实例化)——至少 AFAIK。
现在,即使在 C++11 之前的时代,我们也使用类似的方法将模板类的声明/定义与其实例化分开,以加快编译速度,例如像这样:
point.h:类定义
template <int dim> struct Point {
...
void foo();
...
};
point.cpp:方法定义
#include "point.h"
template <int dim>
void Point<dim>::foo() {
...
}
point_2d.cpp:类实例化(2D 版本)
#include "point.cpp"
template struct Point<2>;
point_3d.cpp:类实例化(3D 版本)
#include "point.cpp"
template struct Point<3>;
main.cpp:2D和3D点的使用
#include "point.h"
int main(int, char**) {
Point<2> p;
p.foo();
}
现在我想知道:
- 我们的方法是有效的 C++(03 或 11)代码还是我们只是幸运地成功了?
- 使用 C++11,我们是否能够通过在
main.cpp中包含point.cpp并声明extern template <int dim> struct Point;来实现相同的目标?
【问题讨论】:
标签: c++ templates c++11 explicit-instantiation