C++11's user defined literals are super cool!
What are user defined literals?
This is a small feature added with c++11 revision which I think is super fancy. In short, you can define your own unit system when declaring variables and each literal’s value, prior to its usage will be put through the operator appropriate to the types and suffixes used. cppreference page describes everything in great details. This sounds a bit unclear but the examples will summarise everything, I promise.
Kilobytes, Megabytes …?
Let’s assume you wish to declare a 1MB buffer. Normally you’d do something like:
char buffer[ 1 * 1024 * 1024 ];
This is of course correct but here’s where the user literals come into play allowing you to make the declaration a lot more concise:
char buffer [ 1_MB ];
That’s it! How does it work though? A declaration of user literal operator matching the suffix is required. In this case:
|
|
It even works with arithmetic expressions so something like this is possible as well:
auto x = 1_MB + 3_MB
Seconds, milliseconds … ?
User literals are exceptionally handy to use with <chrono>
durations. Normally, to declare a duration you’d use:
|
|
This is cool but can be a bit verbose. User literals come to the rescue:
|
|
With these in hands, I can do the following:
|
|
I’m sure everyone agrees that the latter approach is a lot more expressive and simply nicer.
I just scratched the surface here but hopefully this was compelling enough to convince you that user literals are a very nice addition to the language having a real practical application.