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 91011121314151617181920212223
#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:

123
--------------
### Hello! ###
--------------

References