簡體   English   中英

在模板類實現中分離.h和.cpp文件

[英]Separate .h and .cpp files in template class implementation

我正在嘗試編寫一個模板類,它可以根據我傳遞的<class>形成類。 問題是我不能在同一個.h文件中聲明和定義。 在我的項目中,UTF工具只能使用.cpp文件(代碼覆蓋等)。 我在博客中看到他們說“添加.cpp而不是.h ”。 這是可取的嗎?

Template.h

#ifndef TEMPLATE_H_
#define TEMPLATE_H_

template<class T>
class Template
{
public:
    T Add(T a,T b);
};

#endif /* TEMPLATE_H_ */

Template.cpp

#include "Template.h"

template<class T>
T Template<T>::Add(T a, T b)
{
    return a+b;
}

Main.cpp

#include "Template.cpp" //Is this a good practise? 
#include <iostream>

int main(int argc, char **argv) {
    Template<int> obj;
    std::cout<<obj.Add(3,4)<<std::endl;
}

如果這不可行,那么我該如何解決這個問題呢? export

編譯器需要訪問方法的實現才能實例化模板類,因此最常見的做法是在頭文件中包含模板的 定義 ,聲明該模板在頭文件中定義它們

請參閱為什么模板只能在頭文件中實現?

必須在使用它們的每個翻譯單元中定義模板。 這意味着它們必須在頭文件中定義。 如果您的工具堅持使用擴展名.cpp ,您也可以提供它,就像您一樣。

在這種情況下,您甚至不需要將偽標頭拆分為.h.cpp 你可以把它全部放在.cpp#include中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM