Skip to content

Feature discussion: formatting at compile-time #1895

Description

@alexezeder

Recently I tried to use {fmt} in compile-time, not some FMT_STRING compile-time checking or FMT_COMPILE compile-time format string, but using fmt::format_to with arguments in compile-time, like this:

#include <fmt/format.h>

constexpr auto get_formatted_string() {
    std::array<char, 30> buffer{};
    fmt::format_to(buffer.data(), "The answer = {}", 42);
    return buffer;
}

int main() {
    constexpr auto formatted_string = get_formatted_string();
    printf("%s", formatted_string.data());
    return 0;
}

In this example compiler should just format "The answer = {}" with argument 42 into formatted_string array at compile-time. But since {fmt} probably was not planned to be used that way there are plenty of compilation errors with this example.

By adding a constexpr keyword where it's needed, replacing some std:: entities to constexpred self-written ones and using C++20 std::is_constant_evaluated to eliminate usages of non-constexpr functions, I was able to format integers and strings into the buffer at compile-time. But then I tried to format a floating point number and realized that code for floating point formatting, besides of using maybe not compile-time friendly algorithms, uses dynamically growing memory_buffer.

Despite I am pretty sure that I will be able to force floating point formatting to work at compile-time some time later, I decide to pause my work on this to get some feedback in advance.

So, will this ability be useful for everyone, or not? Because I was just experimenting, there is no need for me to do formatting in compile time. Are there any similar or worse pitfalls you can think of?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions