Templates and explicit specializations

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.))





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


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);
// ~~~~~





This changes the original template so it won't accept pointers to non-const objects anymore.
– VTT
4 hours ago







@VTT What do you mean "change the original template"? Which part?
– songyuanyao
4 hours ago





Original template was maxn(T *, int);, not maxn(const T *, int);
– VTT
4 hours ago




maxn(T *, int);


maxn(const T *, int);





@VTT But OP said, "And I want to add const,..." After adding const OP got the errors, then OP asked how to solve it, I think.
– songyuanyao
4 hours ago




const





yes, but i think it was supposed to be "to add const tp specialization"
– VTT
4 hours ago





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.

Popular posts from this blog

Keycloak server returning user_not_found error when user is already imported with LDAP

PHP parse/syntax errors; and how to solve them?

How to scale/resize CVPixelBufferRef in objective C, iOS