我讀的書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