Pretty-printer for C++

For all the C++ developers who have ever felt the need to print different types of objects in your source code in a neat and structured format ( perhaps for debugging ), I have developed a set of function templates to ease your pain.

Pretty-print.hpp

Usage -:

example1.cpp
example2.cpp

Now, after looking at the code, you might be wondering why is the overload of operator<< for an array is so much different from that of the rest of the data types.

This is because there is already an implementation of operator<< for arrays in C++.
operator<< has two overloaded versions, one for const void* and the other for const char*.

A char array is converted to const char* and passed to that overload, because it fits better than to const void*.
The int array, however, is converted to const void* and passed to that version.
The version of operator<< taking const void* just outputs the address, whereas the version taking the const char* actually treats it like a C-string and outputs every character until the terminating null character.

All this can be seen in action here.

Therefore, by overloading the operator<< for an array, we are creating an ambiguity for the compiler.
You can confirm it yourself by trying to compile this, and reading the error given by the compiler in which the multiple ambiguous declarations are pointed out.
[ TIP : Execute g++ example4.cpp 2>log.txt to redirect the compilation error to a file for convenience. ]

We can overcome this problem using some ‘template wizardry’.
By using the enable_if template feature to explicitly specify the types for which a function is overloaded, we can instruct the compiler to not call our custom overloaded function if the operator<< is called with a char array.

Advertisements

One thought on “Pretty-printer for C++

  1. I have noticed you don’t monetize anmolsinghjaggi.com, don’t waste your traffic, you
    can earn extra cash every month with new monetization method.

    This is the best adsense alternative for any type of website (they
    approve all websites), for more info simply search in gooogle:
    murgrabia’s tools

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s