Custom {fmt} formatting function with compile time format string checking
Asked Answered
S

1

7

I've got my own logging functions. I want to use libfmt to format the log parameters, eg:

log_error("Error on read: {}", errMsg);

However compile time format string checking seems to only work if I call the print/format functions directly, not if I call them in my log function:

#include <fmt/format.h>

template<typename ...Args>
void log_error(fmt::string_view format, const Args& ...args) {
    // Log function stripped down to the essentials for this example
    fmt::print(format, args...);
}

int main()
{
    // No errors on this line
    log_error(FMT_STRING("Format with too few and wrong type arguments {:d}"), "one", 2.0);
    // Compile errors on the next line
    // fmt::print(FMT_STRING("Format with too few and wrong type arguments {:d}"), "one", 2.0);
}

The above code and the error (if second line is uncommented) can be seen on godbolt

Is there any way to get this compile time format check to work in my own log function?

Spondylitis answered 13/9, 2019 at 10:8 Comment(0)
S
5

You can pass the format string as another template to the custom log_error implementation. Example:

template<typename Str, typename ...Args>
void log_error(const Str& format, const Args& ...args) {
    fmt::print(format, args...);
}

This produces the same error as the direct invocation.

Stillage answered 13/9, 2019 at 10:12 Comment(1)
This no longer seems to work with fmt version 9: ‘format’ is not a constant expressionRoemer

© 2022 - 2024 — McMap. All rights reserved.