如何构建模板的显式实例化以提高编译速度?
How to structure explicit instantiation of a template for compilation speed?
我特别问文件结构以及放什么。考虑以下内容(这是我当前结构的示例(:
Foo.H包括:
template <typaname T>
class Foo {
void bar();
}
#include "foo-inl.h"
Foo-inl.H包括:
template<typaneme T>
void Foo::bar() {
}
一些baz.cpp有:
#include "foo.h"
Foo<X> foo;
其他一些nom_test.cpp有:
#include "foo.h"
Foo<TestY> foo;
如何重构它以利用生产代码 (baz.cpp( 和测试代码 (nom_test.cpp( 中的显式实例化。注意,我不想将测试类型公开给生产版本。
foo.h:
template <typename T>
class Foo {
void bar();
}
#include "foo-inl.h"
extern template class Foo<X>; // means "Foo<X> is instantiated elsewhere"
foo-impl.cpp:
#include "foo.h"
template class Foo<X>; // instantiates Foo<X> here
巴兹.cpp:
#include "foo.h"
// can simply use Foo<X>, the impl will be linked from foo-impl.o
同样,对于测试版本,foo-impl-test.cpp将包含:
#include "foo.h"
template class Foo<TestY>;
请记住,显式实例化模板的语义是不同的 - 它们不再inline
!因此,显式实例化模板的有用性受到限制。C++20 模块以完全不同的、更灵活的方式解决这个问题,因此可能值得等待。