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

Templates, decltype and Overloads All at Once

hardTemplates

📄 Code

Read carefully — what does this print?
1#include <iostream>
2#include <utility>
3 
4template <typename T, typename U>
5auto combine(T first, U second) -> decltype(first + second) {
6 return first + second;
7}
8 
9template <typename T>
10void identify(T& value) {
11 std::cout << "L " << value << "\n";
12}
13 
14template <typename T>
15void identify(T&& value) {
16 std::cout << "R " << value << "\n";
17}
18 
19template <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};
27 
28template <typename T>
29int Foo<T>::counter = 10;
30 
31template <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}
36 
37template <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}
42 
43template <typename T>
44void reveal(T&& item) {
45 std::cout << "reveal: " << item << "\n";
46}
47 
48int 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}

🎯 Your Answer