template function

sswang 2003-10-27 10:17:23
//模板1
template < class T >
void printArray ( T * a, int m ) //attention: the star before a
{
for( int i = 0; i < m ; i++ )
cout << a[i];
}
//模板2
template < class T >
void printArray ( T a , int m ) // no star
{
for ( int i = 0; i < m; i++ )
cout << a[i];
}
// test
void main()
{
int a[] = { 1, 2, 3, 4, 5 }
printArray ( a, 5 );
}
? 究竟T 为何类型
...全文
44 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
darcymei 2003-10-28
  • 打赏
  • 举报
回复
vc6.0报错
F:\windows程序设计\backup\backup.cpp(24) : error C2667: 'printArray' : none of 2 overload have a best conversion
F:\windows程序设计\backup\backup.cpp(24) : error C2668: 'printArray' : ambiguous call to overloaded function
Wolf0403 2003-10-28
  • 打赏
  • 举报
回复
嗯,确实是我错了,sorry。
两个模板函数都可以用。同时存在的情况下,Dev-C++ 选择的是

template < class T >
void printArray ( T * a, int m ) //attention: the star before a
{
cout << "a" << endl;
for( int i = 0; i < m ; i++ )
cout << a[i];
}

可能因为第一个参数是指针类型,这个更接近最佳匹配。
darcymei 2003-10-28
  • 打赏
  • 举报
回复
sorry!被误导了,楼主的意思是调用是会绑定哪个吧!
我觉得如果就像你这么写,会报错把,不能够重载,参数不明。
darcymei 2003-10-28
  • 打赏
  • 举报
回复
你不是知道是模板吗,t就是模板类型阿。他会在编译时绑定具体类型。
还有 to Wolf0403(完美废人) 第二个模板函数并不错。只要在传参时绑定*类型的即可,只不过这样写不是很好。
wangyangcheng 2003-10-28
  • 打赏
  • 举报
回复
--------------------Configuration: template2 - Win32 Debug--------------------
Compiling...
template2.cpp
D:\Cpp\Temp\template2.cpp(20) : error C2667: 'printArray' : none of 2 overload have a best conversion
D:\Cpp\Temp\template2.cpp(20) : error C2668: 'printArray' : ambiguous call to overloaded function
Error executing cl.exe.

template2.exe - 2 error(s), 0 warning(s)


以上是VC++6.0中的結果﹐呵呵﹐真是"百花齊放"呀﹐對這樣一段代碼竟然主流的几個編譯器有如此大的區別﹗
在VC6里面我想是樓上說的原因吧。
daizh 2003-10-28
  • 打赏
  • 举报
回复
这是模板函数重载的二义性。T 可以表示T *,所以出现了错误。
leyt 2003-10-28
  • 打赏
  • 举报
回复
VC7.1编译通过
调用第一个
Wolf0403 2003-10-27
  • 打赏
  • 举报
回复
T 根据你传入的参数的类型来确定是什么类型。

int a[] = { 1, 2, 3, 4, 5 }
printArray ( a, 5 );

那么 a 是 int[],则编译器生成一个

void printArray ( int * a, int m ) //attention: the star before a
{
for( int i = 0; i < m ; i++ )
cout << a[i];
}

=============================================

另外,第二个模板函数根本是错的
xianger008261 2003-10-27
  • 打赏
  • 举报
回复
class T
为类类型啊~~~~~~

24,854

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 工具平台和程序库
社区管理员
  • 工具平台和程序库社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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