iT邦幫忙

0

C++程式使用函式範本(Function template) 的疑難請教

  • 分享至 

  • xImage

我設計一個函式使用函式範本(Function template)

//--------------------------------
在tools_hou.h
template <typename T1, typename T2> //class or typename皆可
T1 add(T1 x, T2 y);

//--------------------------------
在tools_hou.cpp
template <typename T1, typename T2> //class or typename皆可
T1 add(T1 x, T2 y)
{
return x + y;
}

//-------------------------------
在主程式Unit8.cpp

#include "tools_hou.h"

__fastcall TForm8::TForm8(TComponent* Owner)
: TForm(Owner)
{
Label1->Caption = add(1,100);
Label2->Caption = add(1.23,100.34);
}
//-------------------------------

結果編譯錯誤,訊息如下:
Build
[Linker Error] Unresolved external 'int add<int, int>(int, int)' referenced from D:\BCB6PROJECTS\UNIT1.OBJ
[Linker Error] Unresolved external 'double add<double, double>(double, double)' referenced from D:\BCB6PROJECTS\UNIT1.OBJ

請問如何解決?
(如果我將add函數寫在主程式內,則無問題)

meebox iT邦新手 5 級 ‧ 2023-10-11 09:49:56 檢舉
單純定義 template 不會產生任何的 code, 所以你的 tools_hou.cpp 並不會產生任何 add 函式。

你應該把 template 的定義從 tools_hou.cpp 中搬到 tools_hou.h 中, 這樣在 Unit8.cpp 中才能得到 template 的定義, 並且依據給定的引數型別產生真正對應的 add 函式。
cpc0935 iT邦研究生 5 級 ‧ 2023-10-12 09:07:27 檢舉
依此解決了,此疑難花費我很多時間。感謝!!
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友回答

立即登入回答