CJCoding With Joseph
15free / daySign inCreate account
← Back to Question List
C++ Code Walkthrough #102

Trace Specialized Counters and Printing Overloads

hardTemplates

📄 Code

Read carefully — what does this print?
1#include <iostream>
2#include <utility>
3 
4template <typename T>
5class Foo {
6 T m_value;
7public:
8 static int counter;
9 Foo(T value) : m_value(value) {}
10 T value() const { return m_value; }
11};
12 
13template <typename T>
14int Foo<T>::counter = 55;
15 
16template <>
17int Foo<double>::counter = 20;
18 
19template <typename T>
20std::ostream& operator<<(std::ostream& os, Foo<T>& foo) {
21 Foo<T>::counter += 1;
22 os << "lvalue " << foo.value() << " " << Foo<T>::counter;
23 return os;
24}
25 
26template <typename T>
27std::ostream& operator<<(std::ostream& os, Foo<T>&& foo) {
28 Foo<T>::counter += 2;
29 os << "rvalue " << foo.value() << " " << Foo<T>::counter;
30 return os;
31}
32 
33int main() {
34 Foo<int> a(1);
35 Foo<int> b(2);
36 Foo<double> d(2.5);
37 std::cout << a << "\n";
38 std::cout << b << "\n";
39 std::cout << Foo<int>(3) << "\n";
40 std::cout << d << "\n";
41 std::cout << std::move(d) << "\n";
42 std::cout << a << "\n";
43 return 0;
44}

🎯 Your Answer