生成用于使用libfmt格式字符串的编译时间函数字符串

发布于 2025-01-28 10:27:20 字数 711 浏览 4 评论 0原文

我想在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

回眸一笑 2025-02-04 10:27:20

格式字符串的类型和函数的返回类型不能为string_view,因为格式字符串是动态构造的,因此使用String_view将导致悬空指针。

另外,fmt ::格式要求格式字符串必须是恒定的表达式。相反,您需要使用fmt :: vformat。这应该有效

static std::string
headerCenter(const std::string& text, const int width, const char fill) {
  // build fmt string
  std::string format = fmt::format("|{{0:{}^{}}}|", fill, width);
  return fmt::vformat(format, fmt::make_format_args(text));
}

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, using string_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 use fmt::vformat. This should work

static std::string
headerCenter(const std::string& text, const int width, const char fill) {
  // build fmt string
  std::string format = fmt::format("|{{0:{}^{}}}|", fill, width);
  return fmt::vformat(format, fmt::make_format_args(text));
}

Demo

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文