Forward to fmt::format

Kent - October 13, 2023

Sometimes it is desirable to use a formatted string when building messages and when throwing exceptions. Using fmt::format() or std::format() on a function call is not too ergonomical.

int foo = 42;
throw CustomException(fmt::format("Foo is {:d}", foo));

Compare it to:

int bar = 43;
throw CustomException("Foo is {:d}", bar);

The latter case is much more ergonomical and simpler to use. The gist of it is forward the string and arguments to a custom constructor, which uses perfect forwarding to do formatting,

class CustomException : public std::runtime_error {
   public:
    template <typename... Args>
    explicit CustomException(fmt::format_string<Args...> s, Args &&...args)
        : runtime_error(fmt::format(s, std::forward<Args>(args)...)) {}
};

// usage
void formatter() {
    int foo = 42;
    throw CustomException("Foo is {:d}", foo);
}

See Also

Comments

Any comments? Create a new discussion on GitHub.
There used to be an inline comment form here, but it was removed.