不如std::bitset
,但你可以使用位域的整個結構存儲在一個字節:
struct status {
public:
status(Busy busy, Speed speed, Powered powered, Direction direction)
: busy{busy}, speed{speed}, powered{powered}, direction{direction}, pad{0} {};
Busy busy : 1;
Speed speed : 2;
Powered powered : 1;
Direction direction : 1;
unsigned char pad : 3; // pad to 8 bits
};
全部程序:
#include <bitset>
#include <iostream>
#define ENUM_MACRO3(name, v1, v2, v3)\
enum class name : unsigned char { v1, v2, v3};\
std::ostream& operator<<(std::ostream& os, name var) {\
switch (var){\
case name::v1: return os << #v1;\
case name::v2: return os << #v2;\
case name::v3: return os << #v3;\
}\
return os;\
}
#define ENUM_MACRO2(name, v1, v2)\
enum class name : unsigned char { v1, v2};\
std::ostream& operator<<(std::ostream& os, name var) {\
switch (var){\
case name::v1: return os << #v1;\
case name::v2: return os << #v2;\
}\
return os;\
}
ENUM_MACRO3(Speed, fast, medium, slow)
ENUM_MACRO2(Busy, handling, not_handling)
ENUM_MACRO2(Powered, on, off)
ENUM_MACRO2(Direction, forwards, backwards)
struct status {
public:
status(Busy busy, Speed speed, Powered powered, Direction direction)
: busy{busy}, speed{speed}, powered{powered}, direction{direction}, pad{0} {};
Busy busy : 1;
Speed speed : 2;
Powered powered : 1;
Direction direction : 1;
unsigned char pad : 3; // pad to 8 bits
};
int main()
{
status s{Busy::not_handling,Speed::slow,Powered::off,Direction::backwards};
std::cout << "Data has size of " << sizeof(status) << '\n';
std::cout << "busy :" << s.busy << '\n';
std::cout << "speed :" << s.speed << '\n';
std::cout << "powered :" << s.powered << '\n';
std::cout << "direction :" << s.direction << '\n';
unsigned char val = reinterpret_cast<unsigned char&>(s);
unsigned int num{val};
std::cout << num << '\n';
std::bitset<8> bs{num};
std::cout << bs << '\n';
return 0;
}
產地:
Data has size of 1
busy :not_handling
speed :slow
powered :off
direction :backwards
29
00011101
幾點要牢記:
所以你想'散列'這個'結構'? – NathanOliver
嗯...有趣...好吧是一個散列函數..如果生成的密鑰是一個整數.. –
只是一個建議,而不是你的問題的答案。當'true'和'false'需要解釋並且只有有限的速度值時,可以使用枚舉。像「FORWARD」和「BACKWARDS」這樣的名稱在代碼中易於閱讀,人們無需查詢哪個值是哪個。 – Hayt