use*_*288 1 c++ templates class function-templates
这是一个面试问题,已经完成.
哪条线有错误?
#include<iostream>
template<class T> void foo(T op1, T op2)
{
std::cout << "op1=" << op1 << std::endl;
std::cout << "op2=" << op2 << std::endl;
}
template<class T>
struct sum
{
static void foo(T op1, T op2)
{
std::cout << "sum=" << op2 << std::endl ;
}
};
int main()
{
foo(1,3); // line1
foo(1,3.2); // line2
foo<int>(1,3); // line3
foo<int>(1, '3') ; // line 4
sum::foo(1,2) ; // line 5 ,
return 0;
}
Run Code Online (Sandbox Code Playgroud)
第2行有错误,因为模板参数与定义不匹配.第5行有错误,因为缺少模板参数.
但是,第1行不是错误,我不知道为什么,它是否也错过了模板参数?
谢谢 !
它被称为类型deducition.
在第1行,T可以推导出类型,因为参数op1和op2两者都是int,制作T一个int.
在第2行,你传递一个int和一个double,而函数接受这两个参数T,编译器不知道是T应该是a double还是a int.
第3行很好,因为你指定了特化int和传入int(使专业化多余,但完全没问题).
第4行是正常的,因为您声明T为int,然后将char值'3'转换为其数值int.
第5行是一个错误,因为您正在访问一个函数,该函数从它所在的模板化结构中获取其类型,并且类型推导仅适用于函数.