根据我对模板的理解,
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;
}
模板是通用的,并且允许您放置任何数据类型吗?如果是这样,我的计划不应该合法吗?
答案 0 :(得分:3)
如果是这样,我的计划是否合法?
没有。简单来说,您可以将模板参数it
视为类型的占位符。但是it
是两个参数的类型,因此您最终会得到foo(int,int)
或foo(string, string)
。而是使用第二个模板参数:
template<class T, class U>
foo(T num1, U alp)
{
num1=30;
alp="Name";
cout<<num1<<endl;
cout<<alp<<endl;
}
答案 1 :(得分:0)
在使用模板编译器时,在内部使用您提供的类替换您案例中it
的所有用法。因此,只有当您提供给它的类定义为operator=(&it, const char*)
和operator=(&it, int)
时,您的代码才合法,但它不适用于int
“class”或string
。