Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

explicit specialization for function template c++

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)
{
    char a = toupper(testValue);
    char b = toupper(minimum);
    char c = toupper(maximum);
    return a >= b && a <= c;
}

This is the function template, somehow in main when validate function is called, it never uses the second function(the one for const char&) even when the parameters are char. Can anyone see where my problem is?

like image 792
Andy Avatar asked Jan 23 '26 17:01

Andy


1 Answers

The type you specialized for - const char& does not match what T deduces as when you pass a char - it deduces to char!

(template type parameters can deduce to references only in presence of universal references)

So,

template <> 
bool validate<char> ...

Anyways, why are you not overloading instead?

like image 148
LogicStuff Avatar answered Jan 26 '26 09:01

LogicStuff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!