注册 登录
编程论坛 C++教室

模板函数问题:至诚求助

如果快乐↑ 发布于 2007-09-14 09:21, 458 次点击

#include <iostream>
using namespace std;
template <class Any>
void swap(Any &a, Any &b)
{
Any temp;

temp=a;
a=b;
b=temp;
}
int main()
{

int i=10;
int j=20;
cout << "i, j=" << i << ", " << j << ".\n";
cout << "Using compiler-generated int swapper: \n";
swap(i,j);
cout << "Now i,j=" << i << ". " << j << ".\n";

double x=24.5;
double y=81.7;
cout << "x, y=" << x << ", " << y << ".\n";
cout << "Using compiler-generated int swapper: \n";
swap(x,y);
cout << "Now x,y=" << x << ". " << y << ".\n";

return 0;

}


定义的模板也没什么问题
可调用的时候就报错
万思不解
我刚刚学
真诚感谢大侠们帮小弟看看

[此贴子已经被作者于2007-9-14 9:22:11编辑过]

6 回复
#2
远去的列车2007-09-14 10:03

namespace std 里有这个函数模板的定义,所以你重复定义了

改成 swap1

[此贴子已经被作者于2007-9-14 10:33:33编辑过]

#3
sunkaidong2007-09-14 10:25

#include <iostream>
using namespace std;
template <class T1,class T2>
void swap(T1 *a,T2 *b)
{
T1 temp;

temp=*a;
*a=*b;
*b=temp;
}
int main()
{

int i=10;
int j=20;
cout << "i, j=" << i << ", " << j << ".\n";
cout << "Using compiler-generated int swapper: \n";
swap(&i,&j);
cout << "Now i,j=" << i << ". " << j << ".\n";

double x=24.5;
double y=81.7;
cout << "x, y=" << x << ", " << y << ".\n";
cout << "Using compiler-generated int swapper: \n";
swap(&x,&y);
cout << "Now x,y=" << x << ". " << y << ".\n";

return 0;

}

#4
如果快乐↑2007-09-14 13:27
回复:(远去的列车)namespace std 里有这个函数模板...

原来是这样啊
是不是在MSDN里可以找到这个模板啊?

#5
如果快乐↑2007-09-14 13:28
回复:(sunkaidong)#include using...
谢谢你,
你的结果是对的
可是模板函数变成了两个不同类型
#6
如果快乐↑2007-09-14 13:30

我在百度上也找到了一个解释
大家给点意见


1,传递常数实参,不能使用普通的引用形参,要使用const的。
2,函数实现前缺少模板定义。
修改结果如下:
#include "iostream"

template <class Any>
void swap(const Any &a, const Any &b);

int main()
{
using namespace std;
int i=10;
int j=20;
cout << "i, j=" << i << ", " << j << ".\n";
cout << "Using compiler-generated int swapper: \n";
swap(i,j);
cout << "Now i,j=" << i << ". " << j << ".\n";

double x=24.5;
double y=81.7;
cout << "x, y=" << x << ", " << y << ".\n";
cout << "Using compiler-generated int swapper: \n";
swap(x,y);
cout << "Now x,y=" << x << ". " << y << ".\n";

return 0;
}

template <class Any>
void swap(const Any &a, const Any &b)
{
Any temp;

temp=a;
a=b;
b=temp;
}

#7
远去的列车2007-09-14 15:36

呵呵,楼上的不对哦!

你在函数中改变了参数的值,所以不能声明成 const

而且,调用这个函数时,并没有直接用常量做参数的情况

你改后的函数仍调用了std::swap(int &a, int &b)

不然你按下面这样改改试试
int main()
{
using std::cout;
using std::endl; //没用到

int i=10;
int j=20;
……
}

最初的程序按上面这种方法改就OK

[此贴子已经被作者于2007-9-14 16:01:03编辑过]

1