dbg-macro icon indicating copy to clipboard operation
dbg-macro copied to clipboard

Document dbg_macro::prettyPrint in README (if it's still there)

Open alexeyr opened this issue 3 years ago • 3 comments

I found a Reddit comment saying

If you want to format the output specifically for dbg(), specialize dbg_macro::prettyPrint

If this is officially supported, can you add it to README? And if not, have some alternative?

alexeyr avatar Aug 07 '20 11:08 alexeyr

This is still possible, but the name has changed. You can specialize dbg::pretty_print(std::ostream&, const T&). Here is the builtin example for char:

inline bool pretty_print(std::ostream& stream, const char& value) {
  const bool printable = value >= 0x20 && value <= 0x7E;

  if (printable) {
    stream << "'" << value << "'";
  } else {
    stream << "'\\x" << std::setw(2) << std::setfill('0') << std::hex
           << std::uppercase << (0xFF & value) << "'";
  }
  return true;
}

The Boolean return value determines whether or not the expression and the type name should be printed as well.

add it to README

Sounds good!

sharkdp avatar Aug 12 '20 05:08 sharkdp

Actually does it need to be in namespace dbg or can ADL let you use pretty_print in your own namespace?

alexeyr avatar Apr 05 '21 13:04 alexeyr

I haven't checked, but I'd be fine with a change to use ADL to enable non-dbg-namespace usage.

sharkdp avatar Apr 13 '21 13:04 sharkdp

Is there any reason one should prefer specializing pretty_print over operator<< for user defined datatypes? The latter seems already documented.

winwinashwin avatar Jan 15 '23 14:01 winwinashwin

operator<< on ostream might already be implemented for some types (for other use cases.. with non-ideal output). specializing pretty_print might be needed in those cases. But yeah, I haven't seen any need for this so far, so I'm fine with closing this for now. @alexeyr please report back if you think this should still be resolved.

sharkdp avatar Jan 15 '23 15:01 sharkdp

I don't need it currently. But the point would be to use it when you want different output than operator<<, similarly to Rust's Debug ("should format the output in a programmer-facing, debugging context" vs Display ("for user-facing output").

alexeyr avatar Feb 21 '23 10:02 alexeyr

I don't actually remember why exactly I wanted it originally, I think for something like std::vector<our_type> where we wouldn't want to change the behavior everywhere.

alexeyr avatar Feb 21 '23 10:02 alexeyr