【发布时间】:2009-03-17 01:48:13
【问题描述】:
我使用的库几乎完全由头文件中的模板类和函数组成,如下所示:
// foo.h
template<class T>
class Foo {
Foo(){}
void computeXYZ() { /* heavy code */ }
};
template<class T>
void processFoo(const Foo<T>& foo) { /* more heavy code */ }
现在这很糟糕,因为每当我包含其中一个头文件(实际上我在每个编译单元中都包含许多头文件)时,编译时间难以忍受。
由于作为模板参数我只使用一种或两种类型,我打算为每个库头文件创建一个只包含声明的文件,没有繁重的代码,如下所示:
// NEW: fwd-foo.h
template<class T>
class Foo {
Foo();
void computeXYZ();
};
template<class T>
void processFoo(const Foo<T>& foo);
然后是一个创建我需要的所有实例化的文件。该文件可以一次性单独编译:
// NEW: foo.cpp
#include "foo.h"
template class Foo<int>;
template class Foo<double>;
template void processFoo(const Foo<int>& foo);
template void processFoo(const Foo<double>& foo);
现在我可以在我的代码中包含fwd-foo.h 并且编译时间很短。最后我将链接到foo.o。
当然,缺点是我必须自己创建这些新的fwd-foo.h 和foo.cpp 文件。当然,这是一个维护问题:当一个新的库版本发布时,我必须让它们适应那个新版本。还有其他缺点吗?
我的主要问题是:
我是否有机会从原始foo.h自动创建这些新文件,尤其是fwd-foo.h?我必须对许多库头文件(可能 20 个左右)执行此操作,并且最好使用自动解决方案,尤其是在发布新库版本并且我必须使用新版本再次执行此操作的情况下。是否有任何工具可用于此任务?
编辑:
附加问题:在这种情况下,新支持的extern 关键字对我有何帮助?
【问题讨论】:
标签: c++ templates compilation declaration instantiation