Home > Back-end >  Expecting compilation error but it is not the case
Expecting compilation error but it is not the case

Time:04-07

To compute the maximum of two values, I have a specialized function and a generic templated version of the same function. During testing, I am passing a char and a double as argument to the function and as there is no function that matches the type of arguments, I am expecting the compiler to throw error. But it is not the case

#include <iostream>
using namespace std;

int max(int a, int b) {
    cout << "resolved to max() specialized\n";
    return a > b ? a : b;
}

template<typename T>
T max(T a, T b) {
    cout << "resolved to max() templated\n";
    return a > b ? a : b;
}

int main() {
    cout << max('a',2.1) << "\n";   // why specialized max(int,int) is invoked ?
    return 0;
}

CodePudding user response:

template<typename T>
T max(T a, T b) {
    cout << "resolved to max() templated\n";
    return a > b ? a : b;
}

Here a and b must be of the same type to match the template definition. As 'a' is char and '2.1' is double this template isn't considered.

On the other hand you a have a function that takes two ints. As char and double are both implicitly convertible to int this "overload" is used.

CodePudding user response:

You don't specialize anything here and the overloaded int max(int a, int b) function is not preferred over the template, but is the only choice. If you remove it, the template is not chosen either.

  • Related