Hacker News new | ask | show | jobs
by jheruty 2147 days ago
C++ templates can indeed get crazy, but I miss them in every other language I use. For example, I recently wrote some code in which I needed to know whether or not a member existed in a class, at compile time. Turns out, there's a way to do that in C++ using templates and overload rules:

https://en.wikibooks.org/wiki/More_C++_Idioms/Member_Detecto...

Yes, conceptually it's a bit nuts, but the fact that you can do stuff like this makes it unlikely that you'll ever get completely stuck trying to implement something.

I personally love C++ because it's just a giant bag of tools, even if one of those tools is a footgun.

1 comments

Having experienced similar "ah thank god C++ allows me to do [ridiculous template magic]" moments, 99% of the time it is because the language is forcing you (or leading you) into some kind of design that would have never been necessary in a different language. I have seen many hours/days wasted on using esoteric C++ features in order to get around a language limitation/quirk.

So I am going out on a limb here and assuming that your needing to know whether or not a member exists in a class at compile time is simply something you would never need in a different language because the language would allow you to design for something simpler that satisfies the same requirements. As someone who writes both C++ and C# daily, I often end up comparing the two and most of the time I end up thinking "it's cool that you can do that in C++ but this would have been half the lines and cleaner code in C#".

In my case, I needed to know whether or not a member exists in order to implement object tracking. I basically have a macro that inserts a member into a class, and calls that member's constructor with the "this" pointer of the tracked class. A different function needs to know, at compile time, whether or not a class is tracked, as the way memory is allocated differs.

I didn't want to use inheritance, as tracking is disabled in a shipped build, and I want it to have as little effect on the codebase as possible. So, the simplest option seemed to be to check whether or not the member exists (and assume the name is unique enough an untracked object will not contain it). This was good enough for my purposes.

I'm not as familiar with C#, but attributes seems like a potential alternative, though I'm not sure they can be fully removed from a release build. And, of course, C# is garbage collected, which is not ideal for all types of software. If there is a better alternative, I'd be interested in hearing it though!

Don't get me wrong, I'd absolutely love a "better" C++. Rust is a great language, but I personally don't feel that the safety guarantees are worth it for every class of software. If a video game crashes, the world isn't going to end.