Back to questions
JuniorTheoryCommon
What happens when you build and run this program?
#include <iostream>
template <typename T>
T max_of(T a, T b) {
return a > b ? a : b;
}
int main() {
int n = 1;
double x = 2.5;
std::cout << max_of(n, x);
}It does not compile: T cannot be both int and double at once
- Expecting
2.5: deduction applies no conversions, songivesT=int,xgivesT=double, and the two disagree. - Expecting
2: the first argument has no priority; each argument deducesTon its own, and the results must match.
- How would you change the call so that the program compiles and prints
2.5? - Why does an ordinary function
double max_of(double a, double b)accept the same call?