Context dependant type formatting for Absl::StrFormat?

28 views
Skip to first unread message

Gregg Tavares

unread,
Sep 6, 2024, 3:54:07 PM9/6/24
to Abseil.io
Is it possible and is there an example of making custom type formatter that can switch its output at runtime based on some context?

I think an example might be `class Temperature` and want Absl::StrFormat to output the value as celcius or farenheit depending on context.

You can imagine using this for localization where you'd have some localization context (since any call to StrFormat might be for a different context)

Of the top of my head I could maybe do something like 

     absl::StrFormat("%s%s", context, someType)

where the context object returns the empty string and records the locale and then the formatting for someType looks at the recorded locale. But that info needs to be local to the absl::StrFormat call.

Another idea is to wrap absl::StrFormat in my own  my::StrFormat that does something like

     std::string my::StrFormat(
             Context& context,
             const FormatSpec<Args...>& format,
              const Args&... args) {
         contextStack.push_back(context);
         auto result = absl::StrFormat(format, ...args);
         contextStack.pop_back();
         return result;
     }

And then the custom formatter looks at the top context on the stack. That might work though I'd need to make the stack thread local 

None of these seem ideal.  Am I missing some more obvious solution? Is this just the wrong level to handle this?

Reply all
Reply to author
Forward
0 new messages