简体   繁体   中英

Force compile time error on sizeof operator

Sometimes we have a POD struct whose sizeof has a meaning for serialization purposes. From my PE parser, from example:

struct dos_header {
    unsigned short magic;
    unsigned short cblp;
    ...
    };

This structure is meant to be serialized from/to the PE image, so sizeof on it has a meaning on, say, ifstream::read .

This is invalid of course for non POD. The nt_header for example:

struct nt_header 
{
    std::uint32_t Signature;
    file_header FileHeader;
    std::variant<optional_header_32, optional_header_64> OptionalHeader;
}

Serializing with sizeof would be valid technically, but nonsense at runtime because the size of the structure is run-time dependent.

Is there a way to force the compiler to generate a compile time error when sizeof is used in such a class?

So, if I accidentally use sizeof(nt_header) somewhere, the compiler warns me.

There's no getting around the fact that using even nt_header for memcpy is fine so long as the alternatives are trivially copyable. If that's not the serialization mechanism you want to use for such objects… don't? It's easy to provide a template that handles all your (de)serialization and is specialized to sometimes read less data (and, here, to compute the variant 's index from some other contextual information).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM