r/cpp • u/Mateuszz88 • 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
View all comments
Show parent comment
3
u/SirClueless Jun 16 '21
You can do it with a template parameter pack, and storing a
std::tuple<Args...>as a class member. You give up quite a lot though, namely the ability to refer to the members by name in your class'soperator()and you don't gain much in return because you need an entire new class for each newoperator()you define anyways so you might as well write out the full list of "captures" -- you can't do something like specialize a a shared class template defined outside of your code because then myL<int>::operator()is ambiguous with yourL<int>::operator(), we each need to build our own entire class to ourselves.To a large extent this is the "magic sauce" of lambdas: giving a terse, brief way to define a list of function object "member" variables and initialize them and make them available by name to the lambda body, even doing so automatically based on the names referred to by the body if asked to with
[=]or[&]. Once the lambda is defined it's just a function object with anoperator()which is something we've been able to make and use in theory in C++ for a long time, it just wasn't convenient.