Daily bit(e) of C++ | Explicit object parameter (a.k.a. deducing this)

Šimon Tóth
2 min readOct 9, 2023

Daily bit(e) of C++ #281, C++23 explicit object parameter, a.k.a. deducing this.

C++23 explicit object parameter (a.k.a. deducing this) introduces the ability to name the previously implicit “this” argument explicitly.

This allows for different spellings of method variants (lvalue, const lvalue, rvalue).

Combined with type deduction, it finally allows spelling all three variants as one generic method (significantly reducing code duplication).

// Old spelling
struct Old {
// Also can be spelled as: "void method() {}"
void method() & { /* lvalue */ }
// Also can be spelled as: "void method() const {}"
void method() const& { /* immutable lvalue */ }
void method() && { /* rvalue */ }
};

// New spelling
struct New {
void method(this New&) { /* lvalue */ }
void method(this const New&) { /* immutable lvalue */ }
void method(this New&&) { /* rvalue */ }
};

// One deduced method that handles all three cases
struct Universal {
void method(this auto&& self) {
// Will deduce one of:
// Universal&, const Universal& or Universal&&
}
};

// A practical example of the above
struct Practical {
// Single getter that handles all three variants
auto&& get(this auto&& self) {
// Based on the type of this, forward as lvalue, or rvalue
return std::forward_like<decltype(self)>(self.value);
}
private:
int value = 0;
};

// We can also spell a copy
struct Object {
// Operate on a copy of the object
void method(this Object self) {}
};

// The deduction path can also be used as CRTP replacement
struct InjectMethod {
// Because self is deduced, it will be the static type
// at the call site, i.e. the derived type.
void do_stuff(this const auto& self) {
puts("I did stuff.");
self.do_other_stuff();
}
};

struct Derived : InjectMethod {
void do_other_stuff() const {
puts("And then other stuff.");
}
};

Open the example in Compiler Explorer.

--

--

Šimon Tóth

20 years worth of Software Engineering experience distilled into easily digestible articles.