ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
template <typename T>
T maxVal(T a, T b) { return a > b ? a : b; }
int main() {
    cout << maxVal(3, 7) << " " << maxVal(2.5, 1.5) << " " << maxVal<std::string>("a", "b");
}
  1. A. 7 2.5 b
  2. B. Compile-time error: maxVal cannot be used with both numeric and string types
  3. C. 3 1.5 a
  4. D. 7 1.5 b

Correct answer: A. 7 2.5 b

Templates are instantiated separately for each distinct type used: maxVal<int>(3,7) compares ints (7 wins), maxVal<double>(2.5,1.5) compares doubles (2.5 wins), and the explicitly specified maxVal<std::string>("a","b") compares strings lexicographically ("b" wins). No single generic function is shared across types the way Java's erasure works — each instantiation is its own compiled function.

More OOP with C++ and Java questions

Exams that ask this topic