1

I have a template function as below which has one of the arguments a constant

template<typename T>
T maxAmong( T x, const T y) {
    return x ;
}

For explicit specialization I expected to have the below code. But this gives a compile error.

template<>   char* maxAmong(  char* x, const char* y) {
    return x;
}

Whereas the making both return type and both arguments const works

template<>  const char* maxAmong( const char* x, const char* y) {
    return x;
}

Why does the code in second snippet fail as for me the code looks more right that way.

ArunJose
  • 1,999
  • 1
  • 10
  • 33
  • 1
    `template<> char* maxAmong( char* x, char* const y) {` this is constant pointer. You have pointer to constant, this is a difference. – rafix07 Oct 07 '21 at 06:58
  • In the specialisation I was expecting the type T to be char*. So 1st argument and return type to be char* and second argument a const char*( const of type T as in the original template definition). – ArunJose Oct 07 '21 at 07:01
  • 1
    The second argument is actually a `char* const` not `const char*`. – 康桓瑋 Oct 07 '21 at 07:03

1 Answers1

4

const char * is a pointer to a const char.

char * const is a constant pointer to a char.

Thus, your template specialization should look like this:

template<typename T>
T maxAmong( T x, const T y) {
    return x ;
}

template<> 
char* maxAmong( char* x,  char* const y) {
    return x;
}

This thread might be helpful as well.

What is the difference between char * const and const char *?

schorsch312
  • 5,553
  • 5
  • 28
  • 57