能否在运行时使用自定义格式字符串调用std::format?
能否在std::format中使用运行时定义的格式字符串?
C++20标准明确要求std::format的格式字符串必须是编译时常量,无法直接使用运行时生成或动态传入的格式字符串。这是因为std::format依赖编译时验证格式字符串的语法和类型匹配,以此确保性能与类型安全,这也是你触发error C7595的原因。
你的测试代码问题分析
你代码中的"{0:{1}^{2}}"本身是编译时常量,但报错可能源于两个点:
- 类型不匹配:
width是int类型,而std::format的格式宽度参数期望std::size_t(无符号整数),类型差异导致常量表达式检查失败; - 未定义变量:
main函数中s未声明,属于语法错误。
修正后的代码:
#include <iostream> #include <string> #include <format> std::string centre(std::string& str, std::size_t width, char fillchar = ' ') { if (width <= str.size()) return str; str = std::format("|{0:{1}^{2}}|", str, fillchar, width); return str; } int main() { std::string s = "test"; std::cout << centre(s, 10, '*') << '\n'; }
运行时格式字符串的替代方案
若确实需要使用运行时生成的格式字符串,可使用std::vformat——它接受std::string_view作为格式字符串,无需编译时检查:
#include <iostream> #include <string> #include <format> std::string format_with_runtime_str(std::string_view fmt, auto&&... args) { return std::vformat(fmt, std::make_format_args(args...)); } int main() { // 运行时构造格式字符串 std::string runtime_fmt = "|{0:" + std::string(1, '*') + "}^{1}|"; std::cout << format_with_runtime_str(runtime_fmt, "test", 10) << '\n'; }
你之前能实现类似功能,大概率是使用了编译器非标准扩展,或是C++20标准定稿前的早期实验性实现,那时对格式字符串的常量要求尚未明确。
内容的提问来源于stack exchange,提问作者masher
相关产品推荐
相关产品推荐

