??????
初學(xué)函數(shù)模版,一個(gè)“
bug”
讓俺郁悶了一番,想了一個(gè)小時(shí)都沒有想出所以然。雖求助于網(wǎng)絡(luò),發(fā)貼于
vckbase
。
??????
問題已經(jīng)解決,帖子摘要如下:
主??????題: 函數(shù)模版問題,為什么不能采用多文件方式。? 作??????者: 郭晨 (
書童) 所屬論壇: C++ 論壇 本帖分?jǐn)?shù): 0 回復(fù)次數(shù): 4 發(fā)表時(shí)間: 2006-8-12 19:09:50 正文內(nèi)容: 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; }
可以編譯成功,運(yùn)行得到正確結(jié)果。
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; }
編譯報(bào)告錯(cuò)誤: 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)
//////////////////////////////////// 問題:為什么會(huì)出現(xiàn)這種問題,如何解決?盼賜教。 最新修改:2006-8-12 19:41:10
|
|
回復(fù)人: newgun (
書童)?
|
2006-8-12 19:34:29 (
得分:
10
)?
|
Re:
函數(shù)模版問題,為什么不能采用多文件方式。
在c++標(biāo)準(zhǔn)中規(guī)定可以采用分離的編譯模式,只需要通過在模板定義中的關(guān)鍵字template 之前加上關(guān)鍵字export 來聲明一個(gè)可導(dǎo)出的函數(shù)模板當(dāng)函數(shù)模板,被導(dǎo)出時(shí)我們就可以在任意程序文本文件中使用模板的實(shí)例如:
??// model2.h
// 分離模式: 只提供模板聲明
template <typename Type> Type min( Type t1, Type t2 );
// model2.C
// the template definition
export template <typename Type>????//export關(guān)鍵字
Type min( Type t1, Type t2 ) { /* ...*/ }
????但是好像現(xiàn)在的好多編譯器如vc7都還不支持這種結(jié)構(gòu),所以最好把模板的聲明
和定義都放在頭文件里。
??????
感受:得到網(wǎng)友提示,真有一種“柳暗花明又一村”之感,這個(gè)所謂
bug
是這么簡單又是這么不簡單!
??????
一直認(rèn)為應(yīng)該是自己的錯(cuò)誤,但沒想到是編譯器和標(biāo)準(zhǔn)兼容性的問題。看來自己的思維習(xí)慣應(yīng)該有所改變了。應(yīng)該多角度分析問題,而不能一味的想當(dāng)然。
?????? Ps
:自己也應(yīng)該考慮嘗試一個(gè)新的
C++
編譯器了,老用
vc
,感覺學(xué)的標(biāo)準(zhǔn)
C++
都不純,就象這次事件一樣。