C ++ - Unable to call specialized function

I have the following code:

template<typename T> bool validate(const T& minimum, const T& maximum, const T& testValue) { return testValue >= minimum && testValue <= maximum; } template<> bool validate<const char&>(const char& minimum, const char& maximum, const char& testValue) { // Allows comparisons with char arguments, ignoring case // Localize by calling previously defined function return validate(toupper(minimum), toupper(maximum), toupper(testValue)); } 

The first pattern is used for any types entered, and the specialization is for alphabetic characters. The code compiles and runs with main.cpp to test it, but after testing, I found that specialization is not called. It calls the main template. I can’t understand why.

+4
source share
1 answer

The specialization template <> bool validate<const char&> is selected by the compiler when the template template parameter T is deduced from the main template or explicitly specified as const char& . To call validate('a', 'b', 'c') T char is char , and this does not match the expected specialization.

Or specify a specialization for char (i.e. not const char& ):

 template <> bool validate<char>(const char& minimum, const char& maximum, const char& testValue) { return validate(toupper(minimum), toupper(maximum), toupper(testValue)); } 

or define overload as not a template:

 bool validate(char minimum, char maximum, char testValue) { return validate(toupper(minimum), toupper(maximum), toupper(testValue)); } 
+7
source

All Articles