我的问题是我们应该如何以正确的方式使用模板显式实例化声明?
假设我们有一些模板类template<class T> Foo
。
这是我如何处理此功能的想法:
我们将模板声明放在Foo.h
文件中,将实现放在Foo.inl
文件中,将其包含Foo.inl
在文件末尾,Foo.h
放在. 此外,我们应该在例如文件中使用显式模板实例化定义(当然我们也应该在这个 cpp 文件中包含)。extern template class Foo<int>;
#include "Foo.inl"
Foo.cpp
Foo.h
如果我们做所有这些事情,我们会得到一个错误:我们不能在显式模板实例化声明之后使用显式模板实例化定义。好的,让我们将模板声明和放在单独的文件中,并将其包含在. 最终我们得到了这个:#include "Foo.inl"
Foo.hpp
Foo.cpp
Foo.hpp
template<class T>
class Foo
{
public:
Foo();
...
};
#include "Foo.inl"
Foo.inl
template<class T>
Foo<T>::Foo() {}
Foo.h
#include "Foo.hpp"
extern template class Foo<int>;
Foo.cpp
#include "Foo.hpp"
template class Foo<int>;
并使用此模板,如下所示:
测试1.cpp
#include "Foo.h"
void bar()
{
Foo f;
}
Foo 太多了,你不觉得吗?你如何处理这个问题?
对不起我的英语不好。
更新:
问题不是关于显式模板实例化定义或模板代码本身的配置方法,而是关于显式模板实例化声明的使用以及如果我们尝试使用它会产生“文件地狱”。