C ++相同的模板用于多于1个函数? [英] C++ same template used for more than 1 function?

查看:104
本文介绍了C ++相同的模板用于多于1个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何修改下面的代码,以便我可以使用相同的模板T甚至在call()函数?

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);
 }
}

模板函数与开始。不能将同一模板再次用于另一个函数?有没有其他方法修改上述代码,使我可以使用相同或任何其他模板call()函数?总而言之,我需要使用模板本身来管理所有函数。

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.

推荐答案

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

应该可以工作。

问题可能是因为你有使用命名空间std; ,并且已经存在 std :: swap 不明确。

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

这篇关于C ++相同的模板用于多于1个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆