初学函数模版,一个“
				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
				是这么简单又是这么不简单!
		
		
				
						       
				
				一直认为应该是自己的错误,但没想到是编译器和标准兼容性的问题。看来自己的思维习惯应该有所改变了。应该多角度分析问题,而不能一味的想当然。
		
		
				
						       Ps
				:自己也应该考虑尝试一个新的
				C++
				编译器了,老用
				vc
				,感觉学的标准
				C++
				都不纯,就象这次事件一样。