I was reading https://devblogs.microsoft.com/cppblog/cpp23-deducing-this/ specifically this piece
class cat {
...
//After
template <class Self>
auto&& get_held_toy(this Self&& self) {
return self.held_toy_;
}
//After + forwarding
template <class Self>
auto&& get_held_toy(this Self&& self) {
return std::forward<Self>(self).held_toy_;
}
};
I tried the following code, it still compiles. Is there any specific reason to use template function in Microsoft blog's example?
// turn on c++23
class cat {
...
//After + forwarding
auto&& get_held_toy(this cat&& self) {
return std::forward<Self>(self).held_toy_;
}
};
With this declaration:
The explicit object parameter always has type
cat&&
(that is, an rvalue reference), so you could only call this function on rvalues:It's basically the same as:
Which there is use for, but that isn't "deducing
this
" (it's just an explicit object parameter).The real magic of:
Is that the type of the object parameter, what used to be "
*this
", can be deduced (hence "deducingthis
") from how it is being called:Without having to write 3 different overloads.