User-defined Literals in C++

Written by on March 27, 2016 in C++, Music, Programming with 0 Comments

C++11 introduced user-defined literals, allowing programmers to define special suffixes that can be associated with the built-in literal types: character, integer, float, boolean, and pointer. When designed and used properly, these provide nice syntactic sugar facilitating readability and at the same time, increasing type safety.

For example, I can define an operator _kg that can be suffixed to a float literal to explicitly denote that is a weight expressed in Kilograms. Likewise, I can define an operator for _gm for weight that needs to be expressed in Grams.

long double operator “” _gm (long double val) { return val; }

long double operator “” _kg (long double val) { return val * 1000; }

These can be used as follows:

long double total_weight = 1.5_kg + 25.7_gm;

The leading underscore is mandatory, except for the Standard Library, which can define suffixes without the underscore. In C++14, the Standard Library uses this facility.

For example,

auto my_string = “hello”s;

Here the inferred type of the variable my_string will be the string type because of the s suffix. Note that I did not say “hello”_s.

You can read more about this feature here.

In today’s post, I want to share an interesting use case of this feature. I have been interested in algorithmic music composition for a while, and I have shared some of my experiments in previous blog posts (for example, this one ). I use multiple language environments for my research including Lisp, Mathematica, C++, and Java. So my example for today’s discussion is from music, particularly, expressing note sequences as a user-defined literal.

In MIDI, the note C4, that is the C in 4th octave is usually given the MIDI value of 60. There are 12 elements in each octave, so C5 will be 72, and so on. Wouldn’t it be nice if the programmer can write a MIDI note string as “C#3DE4BbF”_midi, which gets converted to an array of corresponding integers? This will make the program more readable, even without elaborate comments explaining the cryptic string. In the example, the string must evaluate to {49, 62, 64, 70, 65}.

Here is a C++ program to model this user-defined literal.

User-defined Literal

User-defined Literal

I wrote and tested this program in Xcode 7.2.1 on my iMac. You can also see liberal uses of the auto keyword (after C++11, I have become addicted to it as it saves many keystrokes and makes the program more readable!)

You can download the program here.

Tags:

Subscribe

If you enjoyed this article, subscribe now to receive more just like it.

Subscribe via RSS Feed

Leave a Reply

Your email address will not be published. Required fields are marked *

Top