2016-05-18 88 views
1

我读的书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>应该仅实例化一次,但我不知道如何在此示例中使用此技术。

+5

'#包括 “test_tpl.cpp”'? – SergeyA

+0

最后一句中的主张来自哪里? –

+1

另请参阅:[?为什么模板仅在头文件来实现(http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – NathanOliver

回答

1

您将有

//test_tpl.h

template<typename T> 
class Test_tpl 
{ 
public: 
    void func(); 
}; 

//test_tpl.cpp

#include "test_tpl.h" 

template<typename T> 
void Test_tpl<T>::func(){} // in cpp, so only available here 

template void Test_tpl<int>::func(); // Explicit instantiation here. 
            // Available elsewhere. 

//a.cpp 的#include“test_tpl.h显式实例“

// use class Test_tpl<int> here 

//b.cpp 的#include “test_tpl.h”

// use class Test_tpl<int> here 
+0

如果你不在头文件中包含CPP文件,或者没有在头文件中实现所有的模板类,这个过程只会为'func'启用'',并且会导致链接器错误。 – Ajay

+0

@Ajay准确无误。所以看起来,显式实例化可以限制用户使用模板时的实例化。如果我们不想限制它,我认为我们必须在标题中包含CPP文件。 – Yves

+0

@Thomas:不要包含cpp文件,将其重命名为包含.inl,.hxx。 – Jarod42