use*_*472 1 c++ static templates struct
它是一个C++代码,为什么第3行有一个错误:
模板结构和使用没有模板参数
template<class T> void foo(T op1, T op2)
{
cout<< "op1 = " << op1 << endl;
cout<< "op2 = " << op2 << endl;
}
template<class T>
struct sum
{
static void foo(T op1 , T op2)
{
cout << "sum is " << op1 << endl;
}
};
int main()
{
foo(1,3); // line 1
foo<int>(1, '3'); // line 2
sum::foo(1,2); // line 3
return 0;
}
Run Code Online (Sandbox Code Playgroud)
第1行没有模板参数,但没有错误.
谢谢 !
第3行正在尝试使用类模板的成员.
编译器可以/将(至少尝试)推断出函数模板参数的类型.在少数情况下,它无法推断出类型,因此您需要明确指定它.
编译器不会尝试推断类模板参数的类型.
因此,第3行需要像sum<int>::foo(1, 2);.它本身sum只是类模板的名称,而不是类的名称.::需要在类之前的名称(或命名空间).