ProgrammingHardProduct-company placement · C++
What happens?
What happens?
template <class T> T mx(T a, T b) { return a > b ? a : b; }
int main() {
cout << mx(3, 7); // L1
cout << mx(1, 2.5); // L2
cout << mx<double>(1, 2.5); // L3
}- A. It prints 72.52.5
- B. It prints 722.5
- C. Compile-time error at L2: T is deduced as both int and double
- D. Compile-time error at L3
Correct answer: C. Compile-time error at L2: T is deduced as both int and double
Template argument deduction does not perform conversions: from 1 it deduces int, from 2.5 double, a conflict. Specifying T explicitly (L3) turns it into ordinary overload matching, where 1 converts to double.
More OOP with C++ and Java questions
- What is printed? cpp struct A { A() { cout << "A"; } ~A() { cout << "a"; } }; struct B { B() { cout << "B"; } ~B() { cout << "b"; } }…
- Which line fails to compile? cpp string a = "a" + "b"; // L1 string b = string("a") + "b"; // L2 string c = "a" + string("b"); // L3…
- What is printed? cpp int main() { string s = "hi"; try { cout << s.at(1); s.at(5); cout << "X"; } catch (const outofrange&) { cout << "R"…
- What is printed? cpp int main() { map<string, int> m; if (m["x"] == 0) cout << m.size(); cout << m.count("y") << m.size(); }
- What is printed? cpp int main() { set<int, greater<int>> s{3, 1, 3, 2}; for (int x : s) cout << x; cout << s.size(); }
- What is printed? cpp int main() { vector<int> v{1, 2, 3, 2, 4}; v.erase(remove(v.begin(), v.end(), 2), v.end()); cout << v.size() << ":"…