生成用于使用libfmt格式字符串的编译时间函数字符串
我想在Stdout中创建一个漂亮的表。该桌子上有很多主要是编译时字符串的标题。例如:
std::cout << fmt::format("|{0:-^80}|\n", "File Information");
上面的印刷品:
|-----------------------------File Information------------------------------|
我有很多不同类型的填充和对齐宽度。我决定发挥一些辅助功能:
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);
}
编译时我遇到了此错误:
Constexpr function never produces a constant expression
我做错了什么,以及如何正确地做到这一点?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
格式字符串的类型和函数的返回类型不能为
string_view
,因为格式字符串是动态构造的,因此使用String_view
将导致悬空指针。另外,
fmt ::格式
要求格式字符串必须是恒定的表达式。相反,您需要使用fmt :: vformat
。这应该有效demo
The type of the format string and the return type of the function cannot be
string_view
since the format string is constructed dynamically, usingstring_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 usefmt::vformat
. This should workDemo