根据我对模板的理解,
template<class it>
foo(it num1, it num2) //both it forms int
{
num1=30;
num2=20;
cout<<num1<<endl;
cout<<num2<<endl;
}
int main()
{
int num1, num2;
foo(num1,num2)
return 0;
}
如果我希望函数参数的一侧是字符串,而函数参数的另一侧是 int 怎么办
template<class it>
foo(it num1, it alp) //both it on left int, it on right string , if i had declared
// it on right as "string" instead of "it", it works just fine.
{
num1=30;
alp="Name";
cout<<num1<<endl;
cout<<num2<<endl;
}
int main()
{
int num1; string alp;
foo(num1,alp)
return 0;
}
模板是通用的,可以让您放置任何数据类型吗?如果是这样,我的程序不应该是合法的吗?
最佳答案
If so, shouldn't my program be legal?
没有。简单的说,你可以把模板参数it
看成是一个类型的占位符。但是 it
是 both 参数的类型,所以你最终会得到 foo(int,int)
或 foo(字符串,字符串)
。相反,使用第二个模板参数:
template<class T, class U>
foo(T num1, U alp)
{
num1=30;
alp="Name";
cout<<num1<<endl;
cout<<alp<<endl;
}
关于c++ - 使用模板参数定义的两个不同参数首字母创建函数是否错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23142178/