Search code examples
c++string-formattingcompile-timestring-viewfmt

fmt Library - Formatting to a (compile-time) string_view


I would like to use the fmt library to create a string_view from my format args. There is plenty documented about passing in a compile-time string as the format string, however, I want to output a compile-time string, so that I may use it in other static parts of my code. Is there a way to do this? So far, all the functions I have seen return a std::string; I also tried format_to, but it seems to be explicitly disabled for a string_view iterator (which I am assuming wouldn't work compile-time anyway, as it's mutating). It may be simple and I'm just looking in the wrong places, I don't know.

I would like to be able to do something akin to the following:

consteval std::string_view example(unsigned i){
    return fmt::something<std::string_view>("You sent {}"sv, i);
}

So far, this library seems to provide what I need, but, it would be advantageous to avoid a second dependency.


Solution

  • You can do this with format string compilation (FMT_COMPILE):

    #include <fmt/compile.h>
    
    consteval auto example(unsigned i) -> std::array<char, 16> {
      auto result = std::array<char, 16>();
      fmt::format_to(result.data(), FMT_COMPILE("You sent {}"), i);
      return result;
    }
    
    constexpr auto result = example(42);
    

    This gives an array rather than a string_view but you can make one from the other.

    Godbolt: https://godbolt.org/z/TqoEfTfWs