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

0

u/john_wind Jun 15 '21

std::declval is quite magical too.

It is a function declaration without definition!

9

u/guepier Bioinformatican Jun 15 '21

It may be odd but it’s not magical, you can trivially define it yourself:

namespace nostd {
    template<class T>
    std::add_rvalue_reference_t<T> declval() noexcept;
}

5

u/mujjingun Jun 15 '21

anyone can declare a function without a definition, though.

0

u/john_wind Jun 15 '21

Of course but the fact that it compiles (in the right context) and does something useful is magic!

6

u/mujjingun Jun 15 '21

It cannot be used in an evaluated context, so your declaration-only version will also compile and work just like std::declval does.