I am trying to write a template specialization for a function that returns the maximum value of an array of numeric values (general version) or the longest c-string of an array of c-strings (specialization). If I do not use const-ness, my function prototypes look like this
template <typename T>
T maxn(T* my_Tptr, unsigned int n);
template <>
char* maxn <char*> (char** my_cstrings, unsigned int n);
and my code compiles.
However, if I try to use const-ness, my function prototypes look like this,
template <typename T>
T maxn(const T* my_Tptr, unsigned int n);
template <>
char* maxn <char*> (const char** my_cstrings, unsigned int n);
my code does not compile, and the compiler (gcc) prints this error:
error: template-id 'maxn' for 'char* maxn(const char**, unsigned int)' does not match any template declaration.
Where am I going wrong?
The problem is in the const
ness. If you look closely const T* my_Tptr
means my_Tptr is a pointer to const T. But const char** my_Tptr
means Tptr is a pointer to pointer to const char. So the type moves from pointer to const T to pointer to pointer to const T. If you make it char* const* my_Tptr*
then it will work, since then the type will be pointer to const char pointer. The specialization is pointer to const T*->pointer to const char*
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With