簡體   English   中英

在頭文件中包含模板實現cpp文件,並避免鏈接混亂

[英]Include template implementation cpp file in header file and link confusion

我正在閱讀一篇文章《 C ++模板的白痴指南-第2部分》 ,來到了“聲明和實現分離”部分。

現在,我有三個文件,其內容如下:

sample.hpp

#ifndef SAMPLE_HPP
#define SAMPLE_HPP

template <typename T>
void displayValue(T tValue);

#include "sample.cpp"

#endif

將sample.cpp

#include <iostream>
template <typename T>
void displayValue(T tValue){
  std::cout<<tValue<<std::endl;
}

main.cpp中

#include "sample.hpp"
int main(void) {
  displayValue(20);
  displayValue(3.14);
  return 0;
}

根據作者的說法,

您的項目/內部版本現在不得添加Sample.CPP進行編譯

但是,當我使用時:

g++ main.cpp sample.cpp -o main

它仍然有效!

我認為,在這種情況下,對象sample.o仍然包含關於模板函數沒有代碼displayValue ,並在main.o對象,它包含的內容。 因此,理論上沒有錯誤。 但是為什么作者說must not呢?

沒有任何錯誤是正常現象。 因為您的定義和實現被視為一個文件。

更好和通常的C ++風格是;

頭文件(myClass.h):您不應包括實現文件(如果有,則編譯器會找到它)。 實現(myClass.cpp): #include myClass.h

主程序(main.cpp)這也將需要#include myClass.h

如果您使用這種通常的樣式來實現,則僅會因為不應該將模板函數/類的定義和實現分開而得到鏈接錯誤。

作者可能是指此。

模板是部分定義,因此可以將其限定為在標頭中“部分”實現。 就你而言

sample.hpp

#ifndef SAMPLE_HPP
#define SAMPLE_HPP

#include <iostream>
template <typename T>
void displayValue(T tValue){
  std::cout<<tValue<<std::endl;
}
#endif

main.cpp中

#include "sample.hpp"
int main(void) {
  displayValue(20);
  displayValue(3.14);
  return 0;
}

即使您將標頭添加到多個位置(而且可讀性很強),這在任何情況下都可以完美運行

否則,通過將sample.cpp包含在其他使用該模板的cpps中,您仍然可以保留所做的工作並“從理論上來說是正確的”。 還有更多的工作。

注意:這不是問題的確切答案,而是一種繞過包括問題在內的所有問題的方法。

暫無
暫無

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

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