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.you may define a typdef or macro to make it smaller. But it is recommended to put template definitions because it makes the code readable. Also you can encapsulate two functions in a class which is a template.
or something like this if you don't want to use classes also you don't want to use
template<class T>
:The problem is that your #include is bringing in the standard library std::swap template. Because you use "using namespace std" the compiler can't tell which function you want to call, your or the one in the standard library.
You have two choices, either stop using "using namespace std" or be explicit about which swap function you want to call, so in your call function write "::swap(x, y)" instead.
(Note that you DO need to put "template " in the defintion of your call function)