Cling is a pretty cool C++ interpreter built at CERN. C++ workflow feedback loops typically involve writing code, compiling, linking, and running/debugging, which can be lengthy. Cling shortens this by giving users a REPL (Read-eval-print loop), which means that you can type your C++ code, press ENTER and see the result almost instantly.
However, when working with structs, classes etc, one runs into a slight issue – Cling will by default just print the address of the struct, not the contents! Given (this can be pasted into cling):
typedef struct foo_t { int x; int y; } foo; foo a { .x = 1, .y = 2};
we end up with this:
[cling]$ a (foo &) @0x7fbecf181010
Which isn’t all that useful! Various debuggers do better than this, lldb and gdb will e.g. typically print the struct’s members:
(lldb) frame variable a (foo) a = (x = 1, y = 2)
Cling can actually auto-complete the struct members when pressing TAB, but for some reason this isn’t used in the printing logic. It would be cool if in the future this would work out of the box, like with lldb and gdb.
In the mean time, I had a look at how the printing logic worked, and it looks like there’s some neat code to check if an appropriately overloaded printValue function exists, and depending on whether that’s the case or not, either the address will be printed, or the printValue function will be called.
So, let’s follow the example (again, this can be pasted into cling):
#include <sstream> namespace cling { std::string printValue(const foo* f) { std::ostringstream oss; oss << "{.x=" << f->x << ", " << ".y=" << f->y << "}"; return oss.str(); } }
And voilà:
[cling]$ a (foo &) {.x=1, .y=2}
It even works in Jupyter notebooks using the Cling kernel:
