Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fmt compile time format string check without generating asm code for the check?

Tags:

c++

c++20

fmt

Is there anyway to ask fmt library to do compile time check on the format string against the argument types without generating any asm code (to be compiled out)?

For example,

#include <fmt/core.h>
#include <fmt/compile.h>

int main() {
    fmt::format(FMT_STRING("{:d}"), 123);
}

Code above does the check (FMT_STRING is optional for compiler supporting constval) but it also generates some asm code as you can see in the link.

I am looking for a way to trigger the check at compile time without any asm in the final binary. The reason is that I would like to create my own logger (on top of fmt) (similar idea to this) but I would like to defer the actual formatting to another thread later but only have the compile time check done (without any asm code). Is it possible?

like image 637
HCSF Avatar asked Sep 05 '25 03:09

HCSF


1 Answers

Use static_assert to check the return value of formatted_size with FMT_COMPILE macro

static_assert(fmt::formatted_size(FMT_COMPILE("{:d}"), 123));

Demo

like image 191
康桓瑋 Avatar answered Sep 07 '25 20:09

康桓瑋