Home > other >  is std::format at runtime possible?
is std::format at runtime possible?

Time:02-05

Can I use a format string defined at runtime in a std::format?

This seems to say that you can't; that all format strings are a compile-time-only thing. I could have sworn that I did this only a few months ago, maybe it was before the Standard was regressed.

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

std::string centre(std::string& string, const int width, const char fillchar = ' '){
    if (width <= string.size())
        return string;
    
    string = std::format("|{0:{1}^{2}}|", string, fillchar, width); //line 25
    return string;
}

int main() {
   std::cout << centre(s, 10, '*');
}

On building, I get the error

string.cpp(25,24): error C7595: 'std::_Basic_format_string<char,row::string::str &,const size_t &,const char &>::_Basic_format_string': call to immediate function is not a constant expression

CodePudding user response:

Can I use a format string defined at runtime in a std::format?

P2216 makes std::format only accept compile-time string literals. For dynamic format strings, you can use std::vformat.

It's worth noting that std::format still doesn't support parameterized fill characters due to performance issues (see #2189), you may need to construct the format string for the format manually.

std::string centre(std::string string, int width, char fillchar = ' ') {
  if (width <= string.size())
    return string;
  std::string fmt_str = std::format("|{{:{}^{}}}|", fillchar, width);
  return std::vformat(fmt_str, std::make_format_args(string));
}

Demo

  • Related