Don't do it.
There's no such thing in C++ as a "hex pattern"
. What you actually use is an integer literal. See paragraph "The type of the literal"
. Thus, sizeof (0xffff)
is equal to sizeof(int)
. And the bad thing is: the exact size may vary.
From the design point of view, I can't really think of a situation where such a solution is acceptable. You're not even deriving a type from a literal value, which would be a suspicious as well, but at least, a typesafe solution. Sizes of values are mostly used in operations working with memory buffers directly, like memcpy()
or fwrite()
. Sizes defined in such indirect ways lead to a very brittle binary interface and maintenance difficulties. What if you compile a program on both x86
and Motorola 68000
machines and want them to interoperate via a network protocol, or want to write some files on the first machine, and read them on another? sizeof(int)
is 4 for the first and 2 for the second. It will break.
Instead, explicitly use the exactly sized types, like int8_t, uint32_t, etc. They're defined in the <cstdint>
header.