新聞中心
C++編程語(yǔ)言中的模板應(yīng)用是一個(gè)非常重要的操作技巧。它的應(yīng)用在很大程度上提高了編程人員程序開(kāi)發(fā)效率。在這篇文章中,我們將會(huì)重點(diǎn)介紹一下有關(guān)C++模板限制的相關(guān)應(yīng)用,方便大家理解。

1、浮點(diǎn)數(shù)不能作為 非類(lèi)型模板參數(shù) 如:template
2、自定義類(lèi)不能作為模板參數(shù),這些自定義類(lèi)也是 非類(lèi)型模板參數(shù)。
- // 6-14-2009
- #include
- using namespace std;
- // #define FLOAT
- // #define TEMPLATE_OBJECT
- #define COMMON_OBJECT
- #ifdef FLOAT
- template
- class TT;
- #endif
- #ifdef TEMPLATE_OBJECT
- template < class T >
- class TM {};
- template < TM
c > - class TT;
- #endif
- #ifdef COMMON_OBJECT
- class TN{};
- template < TN c >
- class TT;
- #endif
C++模板限制中還有一個(gè),而且相當(dāng)重要:
模板類(lèi)或模板函數(shù)的聲明與定義必須位于同一個(gè)文件中!除非新一代的編譯器支持關(guān)鍵字export.
如果編譯器不支持export關(guān)鍵字,但我們又想把聲明與定義分開(kāi)寫(xiě),那該如何操作呢?方法如下:
把模板聲明寫(xiě)在.h中,模板定義寫(xiě)在.cpp中,需要注意的是,我們并不像一般的文件包含那樣,在.cpp中包含.h,而是在main.cpp中,把這兩個(gè)東東包含進(jìn)來(lái)如:
- // test.h
- template
- class Test
- {
- public:
- void print();
- };
- // test.cpp
- template
- void Test
::print() - {
- cout << "Successfully!" << endl;
- }
- // main.cpp
- #include
- using namespace std;
- #include "test.h"
- #include "test.cpp"
- int main()
- {
- Test
t; - t.print();
- return 0;
- }
以上就是對(duì)C++模板限制的相關(guān)介紹。
【編輯推薦】
- C++字符串分割函數(shù)具體使用方法總結(jié)
- C++異常傳遞三種不同方式介紹
- C++多線(xiàn)程代碼范例剖析
- C++獲得系統(tǒng)時(shí)間不同方案介紹
- C++靜態(tài)成員函數(shù)基本概念講解
網(wǎng)站標(biāo)題:C++模板限制實(shí)際應(yīng)用方式探討
URL標(biāo)題:http://www.5511xx.com/article/dhghoeo.html


咨詢(xún)
建站咨詢(xún)
