2

我可以使用fmt库打印 C++ 类的对象吗?

fmt::print("The object is {}.", obj);
4

2 回答 2

5

是的。您可以按照格式化用户定义类型中所述为您的类型提供formatter专门化来做到这一点:

#include <fmt/format.h>

struct point { double x, y; };

template <> struct fmt::formatter<point> {
  template <typename ParseContext>
  constexpr auto parse(ParseContext &ctx) { return ctx.begin(); }

  template <typename FormatContext>
  auto format(const point &p, FormatContext &ctx) {
    return format_to(ctx.out(), "({:.1f}, {:.1f})", p.x, p.y);
  }
};

您还可以通过组合或继承重用现有的格式化程序,在这种情况下您可能只需要实现该format功能。

于 2019-10-29T04:54:45.847 回答
5

对的,这是可能的。正如评论中所建议的,fmt直接提供对自定义类型的支持:格式化用户定义类型

我通常更喜欢使用std::ostream. 当您实现operator<<自定义类型时,如果您也包含std::ostream自定义类型,fmt则将能够格式化您的自定义类型<fmt/ostream.h>。例如:

#include <fmt/format.h>
#include <fmt/ostream.h>

struct A {};

std::ostream& operator<<(std::ostream& os, const A& a)
{
  return os << "A!";
}

int main()
{
  fmt::print("{}\n", A{});
  return 0;
}

请记住,这种方法可能会比fmt直接通过的最初建议慢得多。

更新:<fmt/ostream.h>为了支持使用比直接通过慢的说法fmt,您可以使用以下基准(使用 Google Benchmark):

#include <fmt/format.h>
#include <fmt/ostream.h>

#include <benchmark/benchmark.h>

struct A {};

std::ostream& operator<<(std::ostream& os, const A& a)
{
  return os << "A!";
}

struct B {};

template<>
struct fmt::formatter<B>
{
  template<typename ParseContext>
  constexpr auto parse(ParseContext& ctx)
  {
    return ctx.begin();
  }

  template<typename FormatContext>
  auto format(const B& b, FormatContext& ctx)
  {
    return format_to(ctx.out(), "B!");
  }
};

static void BM_fmt_ostream(benchmark::State& state)
{
  for (auto _ : state)
  {
    benchmark::DoNotOptimize(fmt::format("{}", A{}));
  }
}

static void BM_fmt_direct(benchmark::State& state)
{
  for (auto _ : state)
  {
    benchmark::DoNotOptimize(fmt::format("{}", B{}));
  }
}

BENCHMARK(BM_fmt_direct);
BENCHMARK(BM_fmt_ostream);

int main(int argc, char** argv)
{
  benchmark::Initialize(&argc, argv);
  benchmark::RunSpecifiedBenchmarks();
  return 0;
}

我机器上的输出:

2019-10-29 12:15:57
Running ./fmt
Run on (4 X 3200 MHz CPU s)
CPU Caches:
  L1 Data 32K (x2)
  L1 Instruction 32K (x2)
  L2 Unified 256K (x2)
  L3 Unified 4096K (x1)
Load Average: 0.53, 0.50, 0.60
***WARNING*** CPU scaling is enabled, the benchmark real time measurements may be noisy and will incur extra overhead.
------------------------------------------------------
Benchmark               Time           CPU Iterations
------------------------------------------------------
BM_fmt_direct          42 ns         42 ns   16756571
BM_fmt_ostream        213 ns        213 ns    3327194
于 2019-10-28T19:44:14.500 回答