【问题标题】:std::format of user-defined types?用户定义类型的 std::format?
【发布时间】:2020-01-25 12:14:03
【问题描述】:

在 C++20 中 - 如何使用户定义的类型与 std::format 兼容?

例如,假设我有一个名为 Point 的类型:

struct Point {
    int x;
    int y;
};

定义了operator<<:

inline std::ostream&
operator<<(std::ostream& o, Point pt)
{ return o << "[" << pt.x << << ", " << pt.y << "]"; }

那么下面的程序会输出Hello [3, 4]!吗?

int main() {
   Point pt{3,4};
   std::cout << std::format("Hello {}!\n", pt);
}

如果是 - 为什么以及如何?

如果不是 - 我必须在 Point 的定义中添加什么才能使其正常工作?

【问题讨论】:

  • @rafix07:您确定该功能已被移植到 C++20 中吗?
  • 你应该重载std::formatter&lt;Ti, CharT&gt;
  • 别忘了投票 =)。

标签: c++ c++20 fmt


【解决方案1】:

std::format 不支持 operator&lt;&lt;,您需要为您的类型 (Point) 提供 formatter 特化。最简单的方法是重用现有的格式化程序之一,例如std::formatter&lt;std::string&gt;:

template <>
struct std::formatter<Point> : std::formatter<std::string> {
  auto format(Point p, format_context& ctx) {
    return formatter<string>::format(
      std::format("[{}, {}]", p.x, p.y), ctx);
  }
};

这将为您提供std::string 支持的所有格式规范,开箱即用。下面是格式化Point 的示例,中心对齐用'~' 填充到10 个字符:

auto s = std::format("{:~^10}", Point{1, 2});
// s == "~~[1, 2]~~"

使用 iostreams 实现这一点并非易事。

【讨论】:

  • 如果给定类型没有std::formatter,那么我们为什么不定义std::format 回退到operator&lt;&lt;(如果有的话)?
  • 退回operator&lt;&lt; 会带来很多问题,例如,输出取决于formatter 专业化的可见性,甚至可能违反ODR。这就是为什么它没有包含在std::format 中。
【解决方案2】:

您必须针对您的类型专门化 std::formatter。

namespace std
{
    template<class CharT>
    struct formatter<Point, CharT>
    {  
        template <typename FormatParseContext>
        auto parse(FormatParseContext& pc)
        {
            // parse formatter args like padding, precision if you support it
            return pc.end(); // returns the iterator to the last parsed character in the format string, in this case we just swallow everything
        }

        template<typename FormatContext>
        auto format(Point p, FormatContext& fc) 
        {
            return std::format_to(fc.out(), "[{}, {}]", p.x, p.y);
        }
    };
}

我认为 ostream 运营商不会起作用,但我没有消息来源支持这种说法。

【讨论】:

  • 标准类型的部分特化是未定义的行为吗?
  • @StaceyGirl 我不这么认为。来自cppreference 的引用:“仅当声明依赖于至少一种程序定义类型 [...] 时,才允许将任何标准库 [...] 模板的模板特化添加到命名空间 std [...]”
  • 你说得对,不支持ostream operator
  • @vitaut 哦,先生。格式化自己以进行救援。感谢您的编辑。从 cppreference 上写的内容不确定。
猜你喜欢
  • 2023-01-03
  • 2016-07-31
  • 1970-01-01
  • 2014-07-02
  • 1970-01-01
  • 2015-03-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-09
相关资源
最近更新 更多