0

I have a

typedef std::array<std::byte, 4> CatType;

And I want to initialize a constant of this type. I can do

const CatType mycat = {std::byte{0x00}, std::byte{0x00}, std::byte{0x00}, std::byte{0x00}};

Which works, but I'd like for readability something like

const CatType mycat = 0x001020ff

Which fails with error

conversion from ‘int’ to non-scalar type ‘const CatType’ {aka ‘const std::array<std::byte, 4>’} requested

1 Answer 1

2

You can define CatType as a wrapper class instead of a typedef, and define a converting constructor from int:

#include <array>
#include <cstddef>

class CatType {
    private:
        std::array<std::byte, 4> m_arr;

    public:
        CatType(int value) :
            m_arr {
                std::byte((value >> 24) & 255),
                std::byte((value >> 16) & 255),
                std::byte((value >> 8) & 255),
                std::byte(value & 255),
            }
        {

        }

        std::byte& operator [](std::size_t index) {
            return m_arr[index];
        }
        std::byte operator [](std::size_t index) const {
            return m_arr[index];
        }
};

If you do not want to create a wrapper class, a user-defined literal (available since C++11) is the closest you can get:

#include <array>
#include <cstddef>

std::array<std::byte, 4> operator ""_arr(unsigned long long value) {
    return std::array<std::byte, 4> {
        std::byte((value >> 24) & 255),
        std::byte((value >> 16) & 255),
        std::byte((value >> 8) & 255),
        std::byte(value & 255)
    };
}

// Usage:
typedef std::array<std::byte, 4> CatType;
int main() {
    const CatType mycat = 0x001020ff_arr;
    return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.