← Back to Question List
C++ Code Walkthrough #102
Trace Specialized Counters and Printing Overloads
📄 Code
Read carefully — what does this print?1#include <iostream>2#include <utility>34template <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};1213template <typename T>14int Foo<T>::counter = 55;1516template <>17int Foo<double>::counter = 20;1819template <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}2526template <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}3233int 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}