2

I have this structure which I need to pass to std::format:

#include <format>
#include <iostream>
#include <sstream>
#include <string>

struct Str {
   int i;
   float f;
   std::string s;
   Str() {}
   Str(int p_i, float p_f, const std::string &p_s) :
      i(p_i), f(p_f), s(p_s) {}

   std::string GetString() {
       std::stringstream ostr;
       ostr << i << " " << f << " " << s;
       return ostr.str();
   }
};

int main() {
    std::string str;
    Str obj(1, 2.3, "test");

    // OK
    str = std::format("Test structure (format) {} {} {}", obj.i, obj.f, obj.s);

    // OK    
    str = std::format("Test structure (format) {}", obj.GetString());

    // Compile time error    
    str = std::format("Test structure (format) {}", obj);
}

Is there a way to pass a whole structure to std::format, instead of having to specify all its fields, or having to convert them to a std::string?

3
  • 2
    There are ways to create custom formatters for user-defined types, you might need to read the documentation from the format library that the standard is based on, perhaps the custom formatting capabilities are in the standard as well. Commented Apr 8 at 15:25
  • godbolt.org/z/9T5dj47f7
    – Marek R
    Commented Apr 8 at 15:40
  • @MarekR - Your implementation deserves a full answer, not a simple comment ;-)
    – Pietro
    Commented Apr 8 at 16:00

1 Answer 1

2

You can use std::formatter. This will allow you to use custom format specifications as well.

3
  • 1
    Not use, but provide own specialization of it.
    – Marek R
    Commented Apr 8 at 15:29
  • 3
    Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference. Commented Apr 8 at 15:52
  • 1
    This seems like a link only answer. Commented Apr 8 at 15:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.