in this program the calling of swap function giving an error called call of overloded function is ambiguos.please tell me how i can resolve this problem. is there is any diffrent method of calling the template function
#include<iostream>
using namespace std;
template <class T>
void swap(T&x,T&y)
{
T temp;
temp=x;
x=y;
y=temp;
}
int main()
{
float f1,f2;
cout<<"enter twp float numbers: ";
cout<<"Float 1: ";
cin>>f1;
cout<<"Float 2: ";
cin>>f2;
swap(f1,f2);
cout<<"After swap: float 1: "<<f1<<" float 2:"<<f2;
int a,b;
cout<<"enter twp integer numbers: ";
cout<<"int 1: ";
cin>>a;
cout<<"int 2: ";
cin>>b;
swap(a,b);
cout<<"After swap: int 1: "<<a<<" int 2:"<<b;
return 0;
}
Your function is conflicting with the one defined in move.h
that is included implicitly by some of your includes. If you remove the using namespace std
this should be fixed - the function you are conflicting with is defined in the std
namespace.
By changing the swap function to my_swap function it solve the problem. because swap is also a predefined function in c++
#include<iostream>
using namespace std;
template <class T>
void my_swap(T&x,T&y)
{
T temp;
temp=x;
x=y;
y=temp;
}
int main()
{
float f1,f2;
cout<<"enter twp float numbers: ";
cout<<"Float 1: ";
cin>>f1;
cout<<"Float 2: ";
cin>>f2;
my_swap(f1,f2);
cout<<"After swap: float 1: "<<f1<<" float 2:"<<f2;
int a,b;
cout<<"enter twp integer numbers: ";
cout<<"int 1: ";
cin>>a;
cout<<"int 2: ";
cin>>b;
my_swap(a,b);
cout<<"After swap: int 1: "<<a<<" int 2:"<<b;
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With