How to Use the Fmt Library To Print Objects

Introduction

{fmt} is a useful library for printing objects with many default types formatted out of the box.

Usage

Simply use FmtApprovals::

For example, vectors are not ostream (<<) printable by default. However, they are with {fmt}. so :

std::vector<int> numbers = {1, 2, 3};
ApprovalTests::FmtApprovals::verify(numbers);

(See snippet source)

This will produce the following output:

{1, 2, 3}

(See snippet source)

note: it is important that we included fmt before approvaltests.

#include <fmt/ranges.h>

(See snippet source)

Installation

Bring your own

ApprovalTests assumes you will add the {fmt} library before including ApprovalTests.hpp. As such it makes no assumptions about fmt. We suggest you read their docs.

If you would like to see how we added fmt to our build, check out:

target_link_libraries(${PROJECT_NAME} fmt::fmt)

(See snippet source)

fmt/CmakeList.txt

fmt/CmakeList.txt.in

Set as default for Approvals

If you wish, you can set FmtApprovals to be the default Approvals with the following line before including ApprovalTests.hpp

#define APPROVAL_TESTS_DEFAULT_STREAM_CONVERTER FmtToString

(See snippet source)