运行时 std::format 可能吗?

mas*_*her 7 c++ c++20 stdformat

我可以使用运行时以 std::format 定义的格式字符串吗?

这似乎是在说你不能;所有格式字符串都是编译时的事情。我可以发誓我是在几个月前才这么做的,也许是在标准回归之前。

#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, '*');
}
Run Code Online (Sandbox Code Playgroud)

在构建时,我收到错误

string.cpp(25,24): 错误 C7595: 'std::_Basic_format_string<char,row::string::str &,const size_t &,const char &>::_Basic_format_string': 对立即函数的调用不是常量表达

康桓瑋*_*康桓瑋 9

我可以在 a 中使用运行时定义的格式字符串吗std::format

P2216只接受std::format编译时字符串文字。对于动态格式字符串,您可以使用std::vformat.

值得注意的是,std::format由于性能问题,仍然不支持参数化填充字符(参见#2189),您可能需要手动构造格式的格式字符串。

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));
}
Run Code Online (Sandbox Code Playgroud)

演示