← Back to Question List
C++ Code Walkthrough #103
Templates, decltype and Overloads All at Once
📄 Code
Read carefully — what does this print?1#include <iostream>2#include <utility>34template <typename T, typename U>5auto combine(T first, U second) -> decltype(first + second) {6 return first + second;7}89template <typename T>10void identify(T& value) {11 std::cout << "L " << value << "\n";12}1314template <typename T>15void identify(T&& value) {16 std::cout << "R " << value << "\n";17}1819template <typename T>20class Foo {21 T m_value;22public:23 static int counter;24 Foo(T value) : m_value(value) {}25 T value() const { return m_value; }26};2728template <typename T>29int Foo<T>::counter = 10;3031template <typename T>32std::ostream& operator<<(std::ostream& os, Foo<T>& foo) {33 Foo<T>::counter += 1;34 return os << "Foo& " << foo.value() << " " << Foo<T>::counter;35}3637template <typename T>38std::ostream& operator<<(std::ostream& os, Foo<T>&& foo) {39 Foo<T>::counter += 2;40 return os << "Foo&& " << foo.value() << " " << Foo<T>::counter;41}4243template <typename T>44void reveal(T&& item) {45 std::cout << "reveal: " << item << "\n";46}4748int main() {49 int n = 4;50 decltype(combine(n, 0.5)) total = combine(n, 0.5);51 std::cout << total << "\n";52 identify(n);53 identify(n++);54 identify(++n);55 std::cout << n << "\n";56 Foo<int> f(n);57 std::cout << f << "\n";58 std::cout << Foo<int>(1) << "\n";59 reveal(Foo<int>(2));60 std::cout << f << "\n";61 std::cout << std::move(f) << "\n";62 return 0;63}