正常
Deducing this (C++23)
One-Liner
Write the first parameter of a member function as this (or a self-chosen name), and the compiler automatically deduces the value category (lvalue/rvalue/const) of the calling object—eliminating the need for the const/non-const/rvalue reference overload trio.
Header
None (language feature)
Core API Cheat Sheet
| Syntax | Description |
|---|---|
this Self&& | Rvalue reference object parameter |
this const Self& | const lvalue reference (read-only) |
this Self& | Non-const lvalue reference (mutable) |
this auto&& | Perfect forwarding, one definition covers all value categories |
| With templates | template<typename Self> this Self&& templated explicit object parameter |
| CRTP Simplification | Explicit object parameters can directly replace CRTP, reducing base class overhead |
Minimal Example
cpp
#include <print>
#include <utility>
struct Widget {
// Explicit object parameter: deduces `self` type based on value category
// If called on lvalue: self = Widget&
// If called on const lvalue: self = const Widget&
// If called on rvalue: self = Widget&&
void print(this auto&& self) {
std::println("Value: {}", self.value);
}
int value{42};
};
int main() {
Widget w;
w.print(); // Deduces Widget&
std::move(w).print(); // Deduces Widget&&
}Embedded Applicability: Moderate
- Reduces boilerplate: One explicit object parameter replaces
const/non-const/rvalue overloads. - Simplifies CRTP: Deduce types directly in member functions, eliminating base class indirection overhead.
- Particularly useful for recursive lambdas and fluent/chaining APIs.
- C++23 feature: Compiler support is still rolling out (GCC 14.1+, Clang 18+, MSVC 19.34+).
- Embedded toolchains have long upgrade cycles: Not suitable for projects requiring broad compatibility in the short term.
Compiler Support
| GCC | Clang | MSVC |
|---|---|---|
| 14.1 | 18 | 19.34 |
See Also
Part of the content referenced from cppreference.com, licensed under CC-BY-SA 4.0