当文件中使用模板时的多文件编译问题
我使用了三个文件template.cpp,myhead.h,myhead.cpp;
内容如下:
//template.cpp
#include <iostream>
#include "myhead.h"
using namespace std;
int main(int argc, char *argv[])
{ int a,b;
a=1,b=2;
cout<<Max(a,b)<<endl;
}
//myhead.h
#ifndef myhead_h
#define myhead_h
template<typename T>
T Max(T ,T ) ;
#endif
//myhead.cpp
#include "myhead.h"
template <typename T>
T Max(T a,T b)
{return (a>b?a:b);}
用borland c++5.5 命令行编译时(bcc32 template myhead)出错如下:
Microsoft Windows XP [版本 5.1.2600]
(C) 版权所有 1985-2001 Microsoft Corp.
E:\BCC55\source>bcc32 template myhead
Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland
template.cpp:
Warning W8057 template.cpp 11: Parameter 'argc' is never used in function main(i
nt,char * *)
Warning W8057 template.cpp 11: Parameter 'argv' is never used in function main(i
nt,char * *)
myhead.cpp:
Turbo Incremental Link 5.00 Copyright (c) 1997, 2000 Borland
Error: Unresolved external 'int Max<int>(int, int)' referenced from E:\BCC55\SOU
RCE\TEMPLATE.OBJ
当把T换成int时编译可以通过,请问这是为什么,谢谢
问题点数:5、回复次数:2Top
1 楼UPCC(杂食动物)回复于 2005-03-11 20:25:40 得分 2
呵呵,摸板是不能分开编译的,要把声明和定义放在同一个文件里 !Top
2 楼q386254779()回复于 2005-03-11 22:20:23 得分 3
模板编译模式分为 “分离模式”和 “包含模式”
你上面的为“分离模式”的近似,只需在头文件中,在模板声明前加上export关键字,
不过目前常用的工具(VC,BCB)都不支持,BCB支持此关键字,不过没有实现其功能
VC 连export都不识别,据说EDG C++支持挺好,不过我是没有。。
UPCC 说的是包含模式
Top



