Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using const char** with Template Specialization

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?

like image 991
jem Avatar asked Nov 01 '22 00:11

jem


1 Answers

The problem is in the constness. 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*

like image 84
Rakib Avatar answered Nov 15 '22 04:11

Rakib