Home > Software design >  Prevent fmt from printing function pointers
Prevent fmt from printing function pointers

Time:11-23

I have a following buggy program. Logic is nonsense, it is just a toy example.

#include <ranges>
#include <iostream>
#include <fmt/format.h>
#include <fmt/ranges.h>

template<typename T>
constexpr bool size_is_4(){
    return sizeof(T)==4;
}

int main() {
    std::cout << fmt::format("float size is 4 bytes  : {}\n", size_is_4<float>);
    std::cout << fmt::format("double size is 4 bytes : {}\n", size_is_4<double>);
} 

output is

float size is 4 bytes : true
double size is 4 bytes : true

The problem is that I pass a function pointer to fmt::format and it prints it out as a boolean. Fix is easy, just invoke the function, but I wonder if there is a way to catch bugs like this.

Since function returns bool it actually looks reasonable as output.

CodePudding user response:

This is a bug caused by function pointers not caught by the pointer detection logic. I opened a GitHub issue: https://github.com/fmtlib/fmt/issues/2609.

CodePudding user response:

You can specialize formatter for functions returning a bool

template <> struct fmt::formatter<bool()>;

but without defining it, so this will give an error.

You can also specialize it for functions returning an arbitrary type

template <typename T> struct fmt::formatter<T()>;

and this gives an error for functions returning, say, an int.

  • Related