Home > OS >  arguments a constant in template function
arguments a constant in template function

Time:10-20

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.

CodePudding user response:

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 *?

  • Related