C++ same template used for more than 1 function?

2019-08-05 10:54发布

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.

3条回答
手持菜刀,她持情操
2楼-- · 2019-08-05 10:55
template <typename T>
void call(T &x, T &y)
{
   swap(x, y);
   cout << x<< y;
}

should work.

The problem is probably because you have using namespace std; and there already exists std::swap, so it's ambiguous.

查看更多
何必那么认真
3楼-- · 2019-08-05 10:59

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.

template<class T>
class XYZ {

void swap(T &x,T &y)
{
 T temp=x;
 x=y;
 y=temp;
}

void call(T &x,T &y)
{
 swap(x,y);
 cout<<x<<y;
}
}

or something like this if you don't want to use classes also you don't want to use template<class T> :

#define templateFor(T) template<class T>

templateFor(T)
void swap(T &x,T &y)
{
 T temp=x;
 x=y;
 y=temp;
}


templateFor(T)
void call(T &x,T &y)
{
 swap(x,y);
 cout<<x<<y;
}
查看更多
等我变得足够好
4楼-- · 2019-08-05 11:05

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)

查看更多
登录 后发表回答