Pretty output formatting in C++11

January 19, 2017 · 1 minute to read · C++, C++11

Let’s use a new C++11 feature: user-defined literal.

Thanks to this one, you could now declare new type from a string or a number. For example "2012-10-30"_date can create a new Date object with these information.

But we could use this feature to other useful things, like format a nice output.

Snippet

Here, some examples:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>

using namespace std;

string operator "" _hr(unsigned long long n)
{
    return string(n, '-');
}

string operator "" _title(unsigned long long n)
{
    return string(n, '#');
}

int main()
{
    cout << 14_hr << endl;
    cout << 3_title << " Hello! " << 3_title << endl;
    cout << 14_hr << endl;

    return 0;
}

Output looks like:

1
2
3
--------------
### Hello! ###
--------------

References