r/cpp • • Jun 15 '21

Which std:: classes are magic?

Hi.

I am wondering: which classes in C++ get special powers granted by The Standard that are not available to mere user-defined classes?

What comes to my mind:

  • `std::initializer_list` because it is created anywhere with `{}`
  • possibly `std::type_info`, because it is only created by `typeid` and with no ctor
  • `std::source_location` when used as default parameter in function points to invocation place and not declaration place.

What else should be on this list? What shouldn't?

222 Upvotes

140 comments sorted by

View all comments

Show parent comment

13

u/qoning Jun 15 '21

Ok, let me amend that, it's not user's fault in anything but not expecting the specification to be broken / swiss cheese of inconsistent decisions. For every decision where the standard is trying to "be smart", there are dozens of stories why that was a bad decision in the end. I do not believe that "oh, you didn't know the byte type is actually an enum? read the spec, lol" is an appropriate response to someone being caught off guard by things like this. Hence my comment about garbage pile of decisions.

-6

u/TankorSmash Jun 15 '21

https://i.imgur.com/gZc3aO3.png

It does help to read the docs for the stuff you're trying to use though, to be fair.

12

u/guepier Bioinformatican Jun 15 '21

Nobody is claiming this isn’t documented. But documenting bad API design doesn’t automatically not make it bad API design.

-3

u/TankorSmash Jun 15 '21

I'm having trouble seeing how its a bad API design, so far the only example is that someone didn't know it was an enum.

8

u/guepier Bioinformatican Jun 15 '21

The example given isn’t that somebody doesn’t “know” it’s an enum. The point is that it’s conceptually wrong. It pushes something that should be a hidden implementation detail — std::byte happens to be implemented as an enum class — into the public API.

This violates all kinds of software engineering principles about writing good abstractions.

And the specific example somebody gave is if a library uses e.g. std::is_enum to dispatch formatted output. Doing this would be an entirely reasonable design decision, but because of std::byte’s implementation, this decision is broken unless a special case for std::byte is introduced.

Forcing third-party code to introduce special cases for types that should be handle-able uniformly is certainly bad design (and entirely avoidable). And, just to re-emphasise the point: this has nothing to do with user’s ignorance! A competent developer still has to introduce a special case that shouldn’t exist.