Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

fmt

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?

like image 951
Mart Avatar asked Sep 13 '19 10:09

Mart


1 Answers

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.

like image 146
lubgr Avatar answered Nov 11 '22 07:11

lubgr