How can I modify the below code so that I could use the same template T even in call() function?
#include<iostream>
using namespace std;
template<class T>
void swap(T &x,T &y)
{
T temp=x;
x=y;
y=temp;
}
/*if i use again the"template<class T>" here i have the error "Identifier T is
undefined" to be gone but then if i compile i have several other errors.. like
"could be 'void swap<T>(T &,T &)' " and some other errors*/
void call(T &x,T &y)
{
swap(x,y);
cout<<x<<y;
}
int main()
{
int num;
cout<<"Enter 1 or 0 for int or float\n";
cin>>num;
if(num)
{
int a,b;
cin>>a>>b;
call(a,b);
}
else
{
float a,b;
cin>>a>>b;
call(a,b);
}
}
A template function is associated with the template declaration at the start. Can’t the same template be used again for another function? Is there an other way to modify the above code so that I could use the same or any other template in call() function? Overall I need to manage all functions using templates itself.
should work.
The problem is probably because you have
using namespace std;and there already existsstd::swap, so it’s ambiguous.