c++ - 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};
};
解决方案
您可以使用由 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
.
推荐阅读
- java - 程序找到数字 n1 的最小排列,但应该大于另一个给定数字 n2;如果不可能,打印“无效”
- c - 从列中获取累积值
- jquery - 固定列宽
- python - 在python中,您是否必须在同一个文件中导入所有依赖库
- android - 如何从 CallScreeningService 中的 Call.Details 中提取电话号码?
- python - 如何正确转换列表的输出值以将它们用作函数内的 args?
- c# - 如何仅使用键盘通过 shell 注册表编辑器来控制我的 wpf 应用程序
- node.js - 如何让 heroku 使用 DB 的环境配置
- google-sheets - 用于过滤 Google 表格中具有最高值的唯一行的公式
- c# - Unity Build 错误:当前上下文中不存在名称“EditorUtility”