sharkdp / dbg-macro

A dbg(…) macro for C++

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

alexeyr opened this issue · 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?

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!

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

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

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

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.

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").

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.