Templates and explicit specializations

时间:2018-07-24 10:12:16

标签: c++ templates template-specialization

I have a template

template<class T>
T maxn(T *, int);

and explicit specialization for char*

template<> char* maxn(char**, int);

And I want to add 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.))

2 个答案:

答案 0 :(得分: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).

template<class T>
T maxn(const T *, int);

template<>
char* maxn<char*>(char* const *, int);
//                      ~~~~~

答案 1 :(得分:2)

You should instantiate the method for const char*:

template<> const char* maxn<const char*>(const char**, int);

template<>char* maxn<char*>(const char**, int); doesn't correspond to

template<class T>
T maxn(T *, int);

signature, so you can't just add const to one parameter.