C ++模板显式实例化声明:最佳实践

时间:2016-11-28 09:22:41

标签: c++ c++11 templates extern explicit-instantiation

我的问题是我们应该如何以正确的方式使用模板显式实例化声明

假设我们有一些模板类template<class T> Foo

我在想如何处理这个功能:

我们在Foo.h文件中放置模板声明,在Foo.inl文件中实现,在Foo.inl文件的末尾包含此Foo.h,在extern template class Foo<int>;之后放置#include "Foo.inl" Foo.cpp。此外,我们应该使用显式模板实例化定义,例如Foo.h文件(当然我们也应该在此cpp文件中包含#include "Foo.inl")。

如果我们做了所有这些事情,我们就会收到错误:我们不能在显式模板实例化声明之后使用显式模板实例化定义。好的,我们将模板声明和Foo.hpp放在单独的文件Foo.cpp中,并将其包含在template<class T> class Foo { public: Foo(); ... }; #include "Foo.inl" 中。最终我们得到了这个:

Foo.hpp

template<class T>
Foo<T>::Foo() {}

Foo.inl

#include "Foo.hpp"
extern template class Foo<int>;

foo.h中

#include "Foo.hpp"
template class Foo<int>;

Foo.cpp中

#include "Foo.h"
void bar()
{
  Foo f;
}

然后使用此模板:

test1.cpp

CLLocationManager

您觉得太多Foo? 您如何应对此问题?

抱歉我的英文。

UPDATE:

问题不在于显式模板实例化定义或在本身配置模板代码的方法,而是关于显式模板实例化声明用法和关于&#34;文件地狱&#34;如果我们试图使用它就会产生。

0 个答案:

没有答案