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
P2216 makes
std::format
only accept compile-time string literals. For dynamic format strings, you can usestd::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.Demo