Search code examples
c++language-lawyerbytestd-byte

Only bitwise operations for std::byte in C++17?


In CPP Reference it is stated that:

std::byte is a distinct type that implements the concept of byte as specified in the C++ language definition.

Like char and unsigned char, it can be used to access raw memory occupied by other objects (object representation), but unlike those types, it is not a character type and is not an arithmetic type. A byte is only a collection of bits, and only bitwise operators are defined for it.

But that's not true: since it is an enumeration type, the compare operations (<, <=, >, >=, ==, !=) are also possible.

Is this intentional, e.g. to use std::byte also as a key for std::map, etc.?


Solution

  • Yes, it's intentional that std::byte has comparison operators. The proposal for std::byte says this:

    Similarly, std::byte can be compared, as comparing and ordering instances is a sensible and useful operation. Given its underlying storage type, the comparison operators would give the same results as if performed on the underlying type.

    - P0298r3 A byte type definition

    As you've pointed out, this allows using std::byte as keys in containers. It also allows using std::byte in algorithms like std::partition, std::sort, std::unique, etc., where equality or less-than comparison is needed.

    Note that the Common definitions library section in the C++ standard doesn't say much about std::byte. It doesn't say that it's not meant to be comparable.

    Keep in mind that cppreference isn't normative, and is editable by anyone* without opening an account. There are numerous sections that are incomplete, and errors frequently make their way into the wiki. Most likely, the author forgot that std::byte also has comparison operators.


    * In fact, I've just edited the page myself, and it now says:

    A byte is only a collection of bits, and only bitwise and comparison operators are defined for it.