Home > Mobile >  -Wstringop-overflow compiler warning in custom fmt::formatter<std::bitset<N>> specializa
-Wstringop-overflow compiler warning in custom fmt::formatter<std::bitset<N>> specializa

Time:01-21

I am trying to create a specialization of fmt::formatter for std::bitset class. However I'm getting an ambiguos warning message from GCC when compiling the below program:

#include <bitset>
#include <cstddef>
#include <fmt/core.h>


template <std::size_t N>
struct fmt::formatter< std::bitset<N> > : fmt::formatter< const char* >
{
/*  constexpr auto parse( format_parse_context& ctx )
    {
        return ctx.begin( );
    }*/

    template <typename FormatContext>
    auto format( const std::bitset<N>& value, FormatContext& ctx )
    {
        return fmt::format_to( ctx.out( ), "{}", value.to_string( ) );
    }
};


int main( )
{
    std::bitset<8> bitset1 { 0b01010101 };
    fmt::print( "bitset1: {}\n", bitset1 );
}

Part of the warning message:

warning: writing 1 byte into a region of size 0 [-Wstringop-overflow=]

How can I fix the issue (if there's actually one)?

Note: I have commented out the parse method and instead inherited from the fmt::formatter<const char*> specialization. This way I don't have to implement the parse method. It compiled without any warnings prior to inheriting from that specialization and commenting out parse.

CodePudding user response:

This warning is a known false positive in some versions of gcc. You can do any of the following to make it go away:

  • Suppress the warning.
  • Switch to a different version of gcc where the warning doesn't occur (see e.g. https://godbolt.org/z/YhdKv4vzM).
  • Use the latest {fmt} from github.
  • Related