Skip to main content
Post Closed as "Duplicate" by user12002570 c++
edited tags
Link
Some programmer dude
  • 408.6k
  • 35
  • 412
  • 642
Source Link
Pietro
  • 13.1k
  • 30
  • 109
  • 204

Can I pass a structure to `std::format`?

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?