新手学模板,遇到了问题,求助
今天刚学模板,写了一个程序,如下
- C/C++ code
#include <cstdlib>#include <iostream>using namespace std;// 交换template <typename T>void swap(T &a, T &b){ T temp; temp = a; a = b; b = temp;}int main(void){ int first = 2, second = 4; swap(first, second); cout << first << " " << second << endl; float fr = 4.0f, sec = 9.0f; swap(fr, sec); cout << fr << " " << sec << endl; system("pause"); return 0;}不知道为何,程序编译不过去。出错信息如下:
1>.\template.cpp(37) : error C2668: “swap”: 对重载函数的调用不明确
1> .\template.cpp(7): 可能是“int swap<int>(T &,T &)”
1> with
1> [
1> T=int
1> ]
1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\utility(16): 或 “void std::swap<int>(_Ty &,_Ty &)”
1> with
1> [
1> _Ty=int
1> ]
1> 试图匹配参数列表“(int, int)”时
1>.\template.cpp(40) : error C2668: “swap”: 对重载函数的调用不明确
1> .\template.cpp(7): 可能是“int swap<float>(T &,T &)”
1> with
1> [
1> T=float
1> ]
1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\utility(16): 或 “void std::swap<float>(_Ty &,_Ty &)”
1> with
1> [
1> _Ty=float
1> ]
1> 试图匹配参数列表“(float, float)”时
[解决办法]
::swap(first, second);
::swap(fr, sec);
[解决办法]
你定义的重载函数没有定义函数体啊
[解决办法]