capypad
0 day streak
cpp / expert
Snippet

C++23 Explicit Object Parameters (Deduced This)

C++23 introduced 'deduced this', allowing member functions to take 'this' as an explicit parameter. This simplifies writing code that depends on the value category (lvalue/rvalue) or the cv-qualifiers of the calling object without duplicating functions.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <typeinfo>
 
struct Logger {
template <typename Self>
void log_type(this Self&& self) {
std::cout << "Called on type: " << typeid(Self).name() << "\n";
}
};
 
int main() {
Logger l;
l.log_type(); // Deduces Logger&
std::move(l).log_type(); // Deduces Logger&&
}
Breakdown
1
void log_type(this Self&& self)
The 'this' keyword before the first parameter makes it an explicit object parameter.
2
template <typename Self>
Self is deduced to the exact type and value category of the object the function is called on.