C 模板類 函式,將標頭檔案與原始檔分離

2021-10-11 09:13:03 字數 2759 閱讀 1614

關鍵在於模板顯式例項化。

按一般方式編寫.h.cpp檔案,但注意新增template的宣告;

.cpp檔案末尾,新增模板顯式例項化**,如:

// 顯式例項化,注意,`template`之後沒有`<>`,若新增則會報錯!

// 每種將被使用的型別,均需要進行顯式例項化

template void a::show(int &&);

template void a::show(double &&);

template void a::show(bool &&);

分開編寫模板類的.h.cpp檔案,注意新增template的宣告;

.cpp檔案末尾,新增類的顯式例項化**,如:

// 只需要class的顯式例項化即可,不需要再寫其成員函式的顯式例項化**

template class base;

在使用該模板類的其他類的.h檔案末尾,新增外部模板類的顯式例項化宣告(僅僅是多了個extern關鍵字):

// 新增這行**的目的,其實是為了消除編譯警告。即便刪掉它,也不會導致編譯錯誤

extern template class base;

前面是簡單描述模板函式/類的原始檔與標頭檔案分離的方法,難免有疏漏。若仍存有疑問,可繼續往下看具體案例。

#ifndef _t_h

#define _t_h

class a

;#endif // _t_h

#include "t.h"

#include using namespace std;

template void a::show(t &&t)

// 顯式例項化,注意,`template`之後沒有`<>`,若新增則會報錯!

template void a::show(int &&);

template void a::show(double &&);

template void a::show(bool &&);

#include #include "t.h"

using namespace std;

int main()

直接編譯即可:

a: t.cpp main.cpp

g++ $^ -o $@ -std=c++17

執行:

./a

​```outputid

b​```end

模板類(基類)

#include class qlabel;

template class base : public qobject

;

#include "base.h"

#include template base::base(qobject *parent)

: qobject(parent)

template base::~base()

template void base::add(t *t)

template void base::remove(t *t)

template void base::remove(int idx)

template t *base::find(int idx) const

/************************************ explicit instantiate *****************************/

template class base;

模板類的普通派生類

#include "base.h"

class qlabel;

class son : public base;

/********************************** explicit instantiate *****************************/

extern template class base;

#include "son.h"

#include son::son(qobject *parent)

: base(parent)

son::~son()

void son::init()

在模板類基類的cpp檔案末尾,新增顯式例項化**:

template class base;
在模板類基類的.cpp檔案開頭,新增包含檔案:

#include
在模板類普通派生類的.h檔案末尾,新增外部宣告**:

extern template class base;

C 模板類與標頭檔案

今天將模板類函式分成了宣告和定義兩個檔案 模板類的宣告 pragma once ifndef find item define find tiem template const elemtype find item const elemtype first,const elemtype last,c...

檔案 標頭檔案 原始檔(C )

標頭檔案和原始檔中的函式宣告與定義 函式原型 file fsopen const char filename,const char mode,int shflag file wfsopen const wchar t filename,const wchar t mode,int shflag 注 ...

模板的宣告和定義 標頭檔案與原始檔

今天,寫了乙個list的模板類,然後把它的宣告和定義分別放在標頭檔案和原始檔中,發現編譯不通。然後,就有疑問了,一是為什麼那些普通類我們分為標頭檔案和原始檔能編譯通過,二是模板為什麼不行,所以這個編譯究竟做了什麼,這才是我的問題。當我們對乙個solution右鍵選擇生成的時候,會對所有的.cpp進行...