Contents

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:

1
2
3
constexpr unsigned long long operator "" _MB(unsigned long long value) {
    return value * 1024 * 1024;
}

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:

1
2
3
auto durationInMs = std::chrono::milliseconds(123);
auto durationInS = std::chrono::seconds(123);
...

This is cool but can be a bit verbose. User literals come to the rescue:

1
2
3
4
5
6
7
constexpr std::chrono::milliseconds operator "" _ms(unsigned long long value) {
    return std::chrono::milliseconds(value);
}

constexpr std::chrono::seconds operator "" _s(unsigned long long value) {
    return std::chrono::seconds(value);
}

With these in hands, I can do the following:

1
2
3
4
auto durationInMs = 123_ms;
auto durationInS = 123_s;
...
std::this_thread::sleep_for(5_s);

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.