1. Problem It Solves
In a deduced T&& parameter, lvalue calls deduce T as a reference; reference-collapsing rules then preserve whether the original argument was lvalue or rvalue. It makes an important constraint visible instead of leaving readers to guess. This lesson keeps only the C++11 core that fits one focused day.
2. Prerequisites
The ideas from Day 33, plus basic variables, functions, and output already introduced.
3. Core Idea
Mental model: In a deduced T&& parameter, lvalue calls deduce T as a reference; reference-collapsing rules then preserve whether the original argument was lvalue or rvalue. Identify the relevant value or state, who owns it, and whether the rule acts during compilation or execution.
4. Minimal Syntax
template<class T> void inspect(T&& value); // T& && collapses to T&5. How It Works
The example creates a tiny fixed state with no keyboard input.
C++11 or the standard-library contract applies today's rule.
The program prints the important result so it can be checked against the source.
6. Common Mistakes
Not every
T&&is forwarding: ifTis not deduced in that call context, the parameter is an ordinary rvalue reference.
7. When to Use It
Use it when a generic function must observe both lvalue and rvalue arguments.
Avoid it when it hides ownership, lifetime, type, ordering, or cost.
8. Simple Example
A trait inside one deduced T&& function reports that a named integer deduces an lvalue reference while a literal does not. The .cpp keeps the data fixed and avoids unrelated abstraction.
Complete sample code
Source file
cpp11/34_forwarding_references_reference_collapsing/main.cpp
#include <iostream>
#include <type_traits>
template <typename T>
void inspect(T&&) {
// For an lvalue call, T is deduced as U& and U& && collapses to U&.
const bool from_lvalue = std::is_lvalue_reference<T>::value;
std::cout << (from_lvalue ? "lvalue" : "rvalue") << '\n';
}
int main() {
int value = 7;
inspect(value); // T becomes int&
inspect(9); // T becomes int
}
9. Key Takeaways
The feature is part of the C++11 scope used in this course.
Understand its lifetime, ownership, type, and ordering consequences.
Compile with warnings and prefer the smallest form that makes the rule obvious.
10. Self-Check Questions
Easy — For
template<class T> void inspect(T&& value), what isTwhen called with anintlvalue and with literal9? Which parameter types result from reference collapsing?Medium — Read the small example described above. What value or state should it print, and which rule produces that result?
Hard — Find and explain the subtle bug in this situation: Not every
T&&is forwarding: ifTis not deduced in that call context, the parameter is an ordinary rvalue reference. What is the smallest C++11-safe correction?