Search code examples
c++functiontemplatescharacterspecialization

Why is my C++ function template specialization not being called?


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.


Solution

  • 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));
    }