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?
Recently I tried to use {fmt} in compile-time, not some
FMT_STRINGcompile-time checking orFMT_COMPILEcompile-time format string, but usingfmt::format_towith arguments in compile-time, like this:In this example compiler should just format
"The answer = {}"with argument42intoformatted_stringarray 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
constexprkeyword where it's needed, replacing somestd::entities toconstexpred self-written ones and using C++20std::is_constant_evaluatedto eliminate usages of non-constexprfunctions, 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 growingmemory_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?