我读的书C++底漆第五版,我得到这个:
C++:什么是显式实例
,当使用一个模板实例化产生的事实(第16.1.1 页。656)意味着相同的实例可能出现在多个目标文件中。当两个或多个单独编译的源文件使用具有相同模板参数的相同模板时,在每个文件中都有该模板的实例化。
我不知道如果我得到它正确,所以我在这里做一个例子:
//test_tpl.h
template<typename T>
class Test_tpl
{
public:
void func();
};
#include "test_tpl.cpp"
//test_tpl.cpp
template<typename T>
void Test_tpl<T>::func(){}
//a.cpp
#include "test_tpl.h"
// use class Test_tpl<int> here
//b.cpp
#include "test_tpl.h"
// use class Test_tpl<int> here
根据上面的段落,在这个例子中,Test_tpl被实例化(Test_tpl<int>
)的两倍。现在,如果我们使用显式实例化,则Test_tpl<int>
应该仅实例化一次,但我不知道如何在此示例中使用此技术。
'#包括 “test_tpl.cpp”'? – SergeyA
最后一句中的主张来自哪里? –
另请参阅:[?为什么模板仅在头文件来实现(http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – NathanOliver