Deducing this (explicit object parameter)
Name the object parameter to deduce its value category and constness.
Problem
C++20 forced you to write 2–4 ref-qualified overloads (const&, &, &&, const&&) to forward `*this` correctly, and CRTP was the only way to get the derived type in a base method.
struct S {
const T& get() const & { return v; }
T& get() & { return v; }
T&& get() && { return std::move(v); }
};#include <utility>
struct S {
T v;
// One template covers every cv/ref combination:
template <class Self>
auto&& get(this Self&& self) {
return std::forward<Self>(self).v;
}
};
// Deducing-this also kills CRTP boilerplate:
struct Base {
template <class Self>
void interface(this Self&& self) { self.impl(); }
};
struct Derived : Base { void impl() { /* ... */ } };
// And enables recursive lambdas without std::function:
auto fac = [](this auto self, int n) -> int {
return n <= 1 ? 1 : n * self(n - 1);
};Notes
- The explicit object parameter replaces the implicit `this`; inside the function `this` is NOT available — use `self`.
- Cannot be combined with static, virtual, or cv/ref qualifiers on the same function.
- Great for de-duplicating getters and for perfect-forwarding call wrappers; enables by-value `this` (e.g. small handles).