Connecting Tech Pros Worldwide Forums | Help | Site Map

Help in template

Member
 
Join Date: Dec 2007
Location: Bangalore India
Posts: 54
#1: Oct 8 '09
Hi,

Please see below a peice of code
Expand|Select|Wrap|Line Numbers
  1. template<class T> void swap(T &a, T &b)
  2. {
  3.         T temp;
  4.         temp = a;
  5.         a = b;
  6.         b = temp;
  7. }
  8.  
Here I am getting an error as below
template.cpp:26: error: call of overloaded swap(int&, int&)â is ambiguous

I dont know what is the problem with swap?

If i define template as as template<class T> void swapa(T &a, T &b) It will work fine. Please help to resolve this.

Thanks
Manjunath

Banfa's Avatar
AdministratorVoR
 
Join Date: Feb 2006
Location: South West UK
Posts: 6,208
#2: Oct 8 '09

re: Help in template


Is there a function with the prototype swap(int&, int&) defined elsewhere in your code?

For instance have you included <algorithm>?
Member
 
Join Date: Dec 2007
Location: Bangalore India
Posts: 54
#3: Oct 8 '09

re: Help in template


I didn't include algorithm. I didn't define swap(int&, int&) too. If I define this one, it should work properly without any error as for as my knowledge.
Correct me if I am wrong.

Thanks,
Manjunath
Banfa's Avatar
AdministratorVoR
 
Join Date: Feb 2006
Location: South West UK
Posts: 6,208
#4: Oct 8 '09

re: Help in template


Well the compiler error means that you have attempted to call swap in a context where it has more than one option of which function to call and no way to resolve which one it should use perhaps you could post the code that is creating the error.
Member
 
Join Date: Dec 2007
Location: Bangalore India
Posts: 54
#5: Oct 8 '09

re: Help in template


Please go through the code and help me out in getting out of that error

#include<iostream>
using namespace std;

template<class T> void swap(T &a, T &b)
{
T temp;
temp = a;
a = b;
b = temp;
}


int main()
{
int a = 100, b = 200;
cout<<"Before swapping"<<endl;
cout<<"a = "<<a<<" "<<"b = "<<b<<endl;
swap(a, b);
cout<<"After swapping"<<endl;
cout<<"a = "<<a<<" "<<"b = "<<b<<endl;
return 0;
}

Thanks,
Manjunath
Needs Regular Fix
 
Join Date: Jul 2008
Posts: 386
#6: Oct 8 '09

re: Help in template


main.cpp:18: error: call of overloaded `swap(int&, int&)' is ambiguous
main.cpp:5: error: candidates are: void swap(T&, T&) [with T = int]
/usr/include/c++/3.3.3/bits/stl_algobase.h:121: error: void
>std::swap(_Tp&, _Tp&) [with _Tp = int]

Because iostream included algorithm.
Either dump 'using namespace std' from your program, place your template in some other namespace or rename it.
Member
 
Join Date: Dec 2007
Location: Bangalore India
Posts: 54
#7: Oct 8 '09

re: Help in template


Ok Thanks for your help Banfa and newb16,

Now I understood whats the problem.

Thanks Once again,
--Manjunath
Reply