Skip to main content

Put those literals into your code

Since we have seen C++11 we obtained an ability to create user defined literals both prefix and suffix forms.
But let's start from the begging, shall we?



So what is literals in the first place? It's a special characters that allows a compiler to know the exact type of a value that you're initialize it with.

So you must have seen them before

0xDEADBEEF
3.14f
429496729u
0010

Those constructions allows you to define type of values to avoid unnecessary copy. Usually it isn't such a big deal but it allows you to write more meaningful code and avoid ambiguity. Wouldn't it be nice to see a expressive and obvious constant instead of just a number that used in N places in a function?

Currently there is a way to create you own useful literals. Those functions can make your code a bit more clean. Using them doesn't solve a problem with magic numbers but makes them more self-explanatory.

But let's get back to the topic.

In the example you can see few literals I've defined to show you some use cases. Those are simple ones but you can make them as complex as you wish. But you need to remember about complexity of those literals. Don't put a for loop over 100.000 elements in it. No really, don't.

Literals have some limitations on defining them. You wont be able to create all possible variations of parameter list. There is more info about it on cppreference.

For me literals is just another way to structure the code in a whole neat package that makes sense for people that see my work. That's the point.

Popular posts from this blog

Extend your list of debug tools with Sanitizers

How many ways to check if code is OK do you know? Probably the one would make a list with debuggers, logging, static/dynamic checkers, profilers and some other tools. The tools the one has in the list are there cause they've been checked with a time. They don't cover all the possible cases of mistakes that could be made during coding phase of a project, but they cover necessary minimum. Today we will try to extend our tool set with a young tools that already got into clang and if you have clang on your machine you can give it a try.

Going up step by step

Have you ever wanted to be able to iterate through your own class as if it was a cool STL container?