当文件中使用模板时的多文件编译问题

pw4394 2005-03-11 08:11:50
我使用了三个文件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时编译可以通过,请问这是为什么,谢谢


...全文
256 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
q386254779 2005-03-11
  • 打赏
  • 举报
回复
模板编译模式分为 “分离模式”和 “包含模式”

你上面的为“分离模式”的近似,只需在头文件中,在模板声明前加上export关键字,
不过目前常用的工具(VC,BCB)都不支持,BCB支持此关键字,不过没有实现其功能
VC 连export都不识别,据说EDG C++支持挺好,不过我是没有。。

UPCC 说的是包含模式

Dong 2005-03-11
  • 打赏
  • 举报
回复
呵呵,摸板是不能分开编译的,要把声明和定义放在同一个文件里 !

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧