This is an example from C++ Primer. Chapter 16. Templates and Generics Programming
There's an example of nontype template parameters.
template<unsigned N, unsigned M>
int compare(const char (&p1)[N], const char (&p2)[M])
{
return strcmp(p1, p2);
}
compare("hi", "mom");
The author stated that
the compiler will use the size of the literals to instantiate a version of the template with the sizes substituted for N and M.
I don't understand this conversion. Why the compiler know it should use the size of the strings to instantiate this template? It it just because the parameters are written in the from of the size of an array?
Thanks.
"hi"
is not a string
, but a string literal, with the type char const [3]
. Similarly, "mom"
has the type char const [4]
.
The compiler simply uses this type information when doing function template argument deduction to deduce the array bounds of these string literal.