I’m a beginner in C++ and using the book “C++ Primer Plus” to teach myself the language as well as to become more comfortable in programming.
I was doing some excersises in the book which are related to the topic of function templates and I have two questions.
I don’t understand why the following explicit specialization doesn’t work:
template <typename T>
T lesser(T a, T b)
{
return a > b ? a : b;
}
template <>
box lesser<box>(box& a, box& b)
{
return a.volume > b.volume? a : b;
}
Assuming I have a structure of type box, why is it not possible to specialize the type to type “box&” but to type “box”? The second declaration means “Don’t use lesser() template to generate a function definition. Instead, use a seperate, specialized function”. And still, I can’t use type box&, only type box. Why is that?
edit: Ok, the second problem just disappeard by itself.
You have to specialize
Tto the same type in every instance:Or you could use
boxin every case.Alternatively, you could change your template to something like:
and specialize it as