2016-05-18 86 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