首页 > 解决方案 > How else can I access a bit field members?

问题描述

So I understand that you can't have pointers to bit-fields because the pointers can only distinguish addresses to the byte level, not bit level. References to bit-fields are also not allowed. Are there any other ways that I would be able to reference the members of the bit field indirectly? Ideally I would be able to access them following using array syntax similar to the mys1array line below. I know arrays of references are illegal but perhaps someone has some sage knowledge out there about some other mechanisms which could achieve a similar goal.

typedef struct{
    unsigned short a : 5;
    unsigned short b : 3;
    unsigned short c : 8;
}myStruct;

class myClass{
public:
    myStruct s1;
    //unsigned short &mys1array[] = {&s1.a, &s1.b ,&s1.c};
};

标签: c++bit-fields

解决方案


您可以使用由 lambda 初始化的函数指针数组来访问具有不同函数的位域的每个元素。

class myClass {
public:
    myStruct s1;
    static constexpr unsigned short (*accessors)(myStruct const &s)[] = {
        +[](myStruct const &s) -> unsigned short { return s.a; }
        // ...
    };
};

有了这个,你必须将一个实例传递myStruct给函数。另一种方法是使用std::function和使用捕获 lambda:

class myClass {
public:
    myStruct s1;
    std::function<unsigned short()> accessors[3];

    myClass(myStruct s)
        : s1(s),
          accessors{
              [this]() -> unsigned short { return this->s1.a; },
              // ...
          }
    {}

    // ...
};

不要忘记,有了这个,您必须实现复制和移动构造函数和赋值运算符,因为 lambda 捕获this.


推荐阅读