5

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 template is used for any inputted types, and the specialization is for literal characters. The code compiles and runs with a main.cpp to test it, but after testing, I found that the specialization isn't being called. It calls the main template. I can't figure out why.

Piotr Skotnicki
  • 46,953
  • 7
  • 118
  • 160
Matt Welke
  • 1,441
  • 1
  • 15
  • 40
  • 2
    you shouldn't specialize for `` case, but for ``, the best would be not to specialize at all, and provide a non-template function overload – Piotr Skotnicki Aug 14 '15 at 13:01
  • When I tried that I get a compiler error: error: template-id 'validate' for 'bool validate(char, char, char)' does not match any template declaration Unfortunately, because this is a homework assignment, I cannot change the code in the main.cpp. I have to use template specialization. – Matt Welke Aug 14 '15 at 13:09
  • 2
    if `T=char` then the parameters shall remain `const char&` – Piotr Skotnicki Aug 14 '15 at 13:12
  • 1
    Code behaved as expected after! Thank you very much. :) – Matt Welke Aug 14 '15 at 13:12

1 Answers1

10

The template <> bool validate<const char&> specialization is picked by a compiler when type template parameter T from the primary template is deduced or specified explicitly to be const char&. For a call validate('a', 'b', 'c'), T is deduced to be char, and this doesn't match what the specialization expects.

Either provide a specialization for char (that is, 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 the overload as a non-template:

bool validate(char minimum, char maximum, char testValue)
{
    return validate(toupper(minimum), toupper(maximum), toupper(testValue));
}
Piotr Skotnicki
  • 46,953
  • 7
  • 118
  • 160