I was reading the book C++ templates - the complete guide, 2nd edition and got the code from that which looks like this:-
template<typename T>
void showVal(const T &arg1, const T &arg2)
{
std::cout << arg1 << arg2;
}
int main() {
showVal("hello", "world1");
return 0;
}
The above code gave me this error:- "error C2782: 'void showVal(const T &,const T &)': template parameter 'T' is ambiguous". This is reasonable because the arguments I am passing are deduced to const char[6] and const char[7]. To fix this, I have made the changes in the function which look like this after the change :-
template<typename T, std::size_t L1, std::size_t L2>
void showVal(const T (&arg1)[L1], const T(& arg2)[L2])
{
std::cout << arg1 << arg2;
}
PS:- I've got this fix from the book
The main confusion underlies in the value of L1 and L2. How compiler knows that it has to pass 6 and 7 to the template parameter L1 and L2. Is there any rule for array type.
"hello"is deduced to beconst char[6], so during the template deduction, the compiler knows thatL1has to be6, since the first argument expects a reference to an array of a typeT(deduced toconst char) of a lengthL1const char[6]andconst char[7]as the types, but you want to know how that works?