Search code examples
c++c++17constexprstdstringfmt

Generating compile time functions string for formatting strings with libfmt


I want to create a nice table in stdout. The table has a lot of headers that are mainly compiletime strings. For example:

std::cout << fmt::format("|{0:-^80}|\n", "File Information");

The above prints:

|-----------------------------File Information------------------------------|

I have lots of different type of fills and align widths. I decided to make some helper functions:

constexpr static
std::string_view
headerCenter(const std::string& text, const int width, const char fill) {

    // build fmt string
    const std::string_view format = "{:" + 'fill' + '^' + toascii(width) + '}';
    return fmt::format(format, text);    
}

I got this error while compiling:

Constexpr function never produces a constant expression

What is it that I am doing wrong, and how to do it correctly?


Solution

  • The type of the format string and the return type of the function cannot be string_view since the format string is constructed dynamically, using string_view will result in a dangling pointer.

    In addition, fmt::format requires that the format string must be a constant expression. Instead, you need to use fmt::vformat. This should work

    static std::string
    headerCenter(const std::string& text, const int width, const char fill) {
      // build fmt string
      std::string format = fmt::format("|{{0:{}^{}}}|", fill, width);
      return fmt::vformat(format, fmt::make_format_args(text));
    }
    

    Demo