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
Tcan be deduced because parametersop1andop2are bothint, makingTanint.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 whetherTshould be adoubleor anint.Line 3 is fine because you specify
intspecialization and passints in as well (making the specialization redundant but perfectly OK).Line 4 is OK because you declare
Tto be an int, then casting thecharvalue of'3'to its numericintvalue.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.