public inbox for gcc@gcc.gnu.org
 help / color / mirror / Atom feed
* Spoofing Rust's `Self` type in C++26
@ 2026-05-09 18:48 Septicake
  0 siblings, 0 replies; only message in thread
From: Septicake @ 2026-05-09 18:48 UTC (permalink / raw)
  To: gcc

[-- Attachment #1: Type: text/plain, Size: 1253 bytes --]

Turns out you can pretty easily spoof a (limited to templated class scope)
`Self` type similar to what appears in Rust through a bit of template
tomfoolery, which I think is really neat and probably already known but I'm
happy about it so :3
Since a base class' templates are resolved effectively "inside" the derived
class, you can have a template default argument like `typename Self = [:
std::meta::current_class() :]` and have it properly resolved to the derived
class. There are some actually useful applications of this, such as for an
object whose methods are intended for chaining, that also inherits from
another class to avoid rewriting similar code, without having to suffer
through casts and pointers along the way. I realized this while messing
around with creating a Java-like factory for annotations, which in and of
itself is already kind of a crime but I like me some good ol'
abstraction, bite me.
Anyway, made a quick example on godbolt and I think it's neat so I wanna
share it:
https://godbolt.org/z/K3zr1o6f3

Is it really necessary to send this to a mailing list? Probably not, it's
certainly not gcc dev focused, but I'm kinda proud of figuring it out so I
wanna brag a tiny bit, sorta like a kid finding a cool rock.

- October

^ permalink raw reply	[flat|nested] only message in thread

only message in thread, other threads:[~2026-05-09 18:49 UTC | newest]

Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2026-05-09 18:48 Spoofing Rust's `Self` type in C++26 Septicake

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).