??????
初學函數模版,一個“
bug”
讓俺郁悶了一番,想了一個小時都沒有想出所以然。雖求助于網絡,發貼于
vckbase
。
??????
問題已經解決,帖子摘要如下:
主??????題: 函數模版問題,為什么不能采用多文件方式。? 作??????者: 郭晨 (
書童) 所屬論壇: C++ 論壇 本帖分數: 0 回復次數: 4 發表時間: 2006-8-12 19:09:50 正文內容: 1) #include <fstream> #include <iostream> using namespace std; template<class Type > Type min(Type a, Type b) { ????return a < b ? a : b; }
int main(int argc, char* argv[]) { ????cout << min(10, 20) << endl; ????return 0; }
可以編譯成功,運行得到正確結果。
2)多文件方式
///////////////////////main.cxx #include "min.h" #include <fstream> #include <iostream> using namespace std; int main(int argc, char* argv[]) { ????cout << min(10, 20) << endl; ????return 0; } ///////////////////////min.h #ifndef _MIN_GHH_ #define _MIN_GHH_??1
template<class Type > Type min(Type a, Type b);
#endif
//////////////////////min.cxx #include "min.h"
template<class Type > Type min(Type a, Type b) { ????return a < b ? a : b; }
編譯報告錯誤: Linking... 20060812_function_template.obj : error LNK2001: unresolved external symbol "int __cdecl min(int,int)" (?min@@YAHHH@Z) Debug/20060812_function_template.exe : fatal error LNK1120: 1 unresolved externals Error executing link.exe.
20060812_function_template.exe - 2 error(s), 0 warning(s)
//////////////////////////////////// 問題:為什么會出現這種問題,如何解決?盼賜教。 最新修改:2006-8-12 19:41:10
|
|
回復人: newgun (
書童)?
|
2006-8-12 19:34:29 (
得分:
10
)?
|
Re:
函數模版問題,為什么不能采用多文件方式。
在c++標準中規定可以采用分離的編譯模式,只需要通過在模板定義中的關鍵字template 之前加上關鍵字export 來聲明一個可導出的函數模板當函數模板,被導出時我們就可以在任意程序文本文件中使用模板的實例如:
??// model2.h
// 分離模式: 只提供模板聲明
template <typename Type> Type min( Type t1, Type t2 );
// model2.C
// the template definition
export template <typename Type>????//export關鍵字
Type min( Type t1, Type t2 ) { /* ...*/ }
????但是好像現在的好多編譯器如vc7都還不支持這種結構,所以最好把模板的聲明
和定義都放在頭文件里。
??????
感受:得到網友提示,真有一種“柳暗花明又一村”之感,這個所謂
bug
是這么簡單又是這么不簡單!
??????
一直認為應該是自己的錯誤,但沒想到是編譯器和標準兼容性的問題??磥碜约旱乃季S習慣應該有所改變了。應該多角度分析問題,而不能一味的想當然。
?????? Ps
:自己也應該考慮嘗試一個新的
C++
編譯器了,老用
vc
,感覺學的標準
C++
都不純,就象這次事件一樣。