是否可以使用C ++中缺少的模板参数调用模板函数? [英] Can a template function be called with missing template parameters in C++ ?
问题描述
这是一个面试问题,已经完成了。
哪一行有错误?
#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;
}
第2行有错误,因为模板参数与定义不匹配。
第5行有错误,因为模板参数丢失。
但是,第1行是一个不是一个错误,我不知道为什么, miss模板参数?
谢谢!
>
在第1行,可以推导出 T
的类型,因为参数 op1
和 op2
均为 int
,使 T
int
。
而在第2行,你传递一个int和一个double,作为 T
,编译器没有线索是否 T
应该是 double
或 int
。
第3行很好,因为你指定 int
专业化并传递 int
(使专业化多余,但完全OK)。
第4行是OK的,因为你声明 T
是一个int,然后转换 char
$ c>'3'到其数字 int
值。
一个错误,因为你正在访问一个函数,从它的模板化的结构它的类型,类型扣除只适用于函数。
This is an interview question, which has been done.
Which line has error ?
#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;
}
Line 2 has error because the template parameter is not matching the definition. Line 5 has error because the template parameter is missing.
But, Line 1 is an not an error, I do not know why, does not it also miss template parameter ?
Thanks !
It's called type deducition.
On Line 1, the type of T
can be deduced because parameters op1
and op2
are both int
, making T
an int
.
Whereas on Line 2, you are passing both an int and a double while the function accepts both parameters as T
, the compiler has no clue whether T
should be a double
or an int
.
Line 3 is fine because you specify int
specialization and pass int
s in as well (making the specialization redundant but perfectly OK).
Line 4 is OK because you declare T
to be an int, then casting the char
value of '3'
to its numeric int
value.
Line 5 is an error because you're accessing a function that gets its type from the templated struct it's in, and type deduction only works for functions.
这篇关于是否可以使用C ++中缺少的模板参数调用模板函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!