問題描述
可能的重復:
為什么應該模板類的實現和聲明在同一個頭文件中?
例如在定義模板類時,為什么類方法的實現需要在標題中?為什么它們不能在實現文件 (cpp/cxx) 中?
e.g when defining a template class why do the implementations of the class methods need to be in the header? Why can't they be in a implementation file (cpp/cxx)?
推薦答案
模板類不是類,而是可用于創建類的模板.當你實例化這樣一個類時,例如MyTemplate
,編譯器當場創建類.為了創建它,它必須查看所有模板化的成員函數(以便它可以使用模板創建實際的成員函數,例如 MyTemplate
),因此這些模板化的成員函數必須在頭文件中.
A template class is not a class, it's a template that can be used to create a class. When you instantiate such a class, e.g. MyTemplate<int>
, the compiler creates the class on the spot. In order to create it, it has to see all the templated member functions (so that it can use the templates to create actual member functions such as MyTemplate<int>::foo()
), and therefore these templated member functions must be in the header.
如果成員不在頭文件中,編譯器將簡單地假設它們存在于其他地方,并從模板化的函數聲明中創建實際的函數聲明,這會導致鏈接器錯誤.
If the members are not in the header, the compiler will simply assume that they exist somewhere else and just create actual function declarations from the templated function declarations, and this gives you linker errors.
"export" 關鍵字應該可以解決這個問題,但很少有編譯器支持它(我只知道 Comeau).
The "export" keyword is supposed to fix this, but few compilers support it (I only know of Comeau).
您也可以顯式實例化 MyTemplate
- 然后編譯器會在編譯包含 MyTemplate
成員函數定義模板.
You can also explicitly instantiate MyTemplate<int>
- then the compiler will create actual member functions for MyTemplate<int>
when it compiles the cpp files containing the MyTemplate
member function definition templates.
這篇關于為什么 C++ 模板定義需要在頭文件中?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!