r/cpp • u/Krystian-Piekos • Apr 08 '26
Hashing in C++26
https://blog.infotraining.pl/hashing-in-cpp-26How to implement hash for custom classes in C++26.
80
Upvotes
r/cpp • u/Krystian-Piekos • Apr 08 '26
How to implement hash for custom classes in C++26.
11
u/BarryRevzin Apr 08 '26
Right now, you're doing this:
You're checking that each base is hashable, but not each member? Also, you're asking for private bases too, but if you get one, your cast won't work.
However, note that you're doing the same exact thing for both base class subobjects and non-static data member subobjects. It's this exact situation why we pushed for allowing you to splice a base class subobject.
So you could write just the one loop to do all the work:
4
u/BarryRevzin Apr 09 '26
Separate comment, I noticed that your mechanism for opting into memberwise hashing is:
This is actually a bad way to opt into something explicitly. For two reasons.
First:
Bexplicitly opts into hashing. ButDis enabled for hashing, even though it did nothing, simply by virtue of inheriting fromB. That's pretty bad in general, but it's especially bad for hashing sinceDmight not be memberwise hashable, and did nothing to explicitly say so, so you might get invalid hashes.Second, there is no way to conditionally opt into this. Say I want to have:
I want
WithIndex<T>to be hashable whenTis. How do I do that? I can't conditionally add a member type alias. I can inherit from a base class that does or doesn't provide that enabling, but that changes the way people interact with my type all of a sudden, so it's not a great approach to have to do.9
u/pdp10gumby Apr 08 '26
I recommend not including the first example of membernumber because it’s fragile, and is followed by a more general (and robust) example.
The reason is that tutorials are often read by people who don’t yet have a good grasp not only of the language, but also of programming in general (this isn’t intended as an insult to the readers btw). As with Stack Overflow, people will often just use the first thing they come across without reading the whole article!
1
u/Realistic-Yak8448 Apr 16 '26
In your Simple Example section, the fourth to last line has a typo in the comment. It should read:
whereas it currently reads:
which is probably a copy/paste error from the preceding Reflection operator section.
-5
u/_Noreturn Apr 08 '26
is this ai generated?