![Creative The name of the picture]()
Templates and explicit specializations
I have a template
template<class T>
T maxn(T *, int);
and explicit specialization for char*
char*
template<> char* maxn(char**, int);
And I want to add const
,
const
T maxn(const T *, int);
but after adding const in explicit specialization there is an error.
template<>char* maxn<char*>(const char**, int);
Why? Who can explain to me?
P.S. Sorry for my English.))
const
2 Answers
2
Given the parameter type const T *
, const
is qualified on T
. Then for char*
(the pointer to char
) it should be char* const
(const
pointer to char
), but not const char*
(non-const pointer to const
char
).
const T *
const
T
char*
char
char* const
const
char
const char*
const
char
template<class T>
T maxn(const T *, int);
template<>
char* maxn<char*>(char* const *, int);
// ~~~~~
maxn(T *, int);
maxn(const T *, int);
const
You should instantiate the method for const char*
:
const char*
template<> const char* maxn<const char*>(const char**, int);
template<>char* maxn<char*>(const char**, int);
doesn't correspond to
template<>char* maxn<char*>(const char**, int);
template<class T>
T maxn(T *, int);
signature, so you can't just add const
to one parameter.
const
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
You get an error because it's not a specialization, but an overload instead. The
const
is a factor in the function signature that changes it from specialization to overload.– Some programmer dude
6 hours ago