有可能以一种相当低效和迂回的方式拼凑出一些充当比特场参考的东西。
template<typename underlying>
struct bitfield_ref
{
virtual underlying get() { return getter(); }
virtual void set(underlying val) { setter(val); }
bitfield_ref(std::function<underlying()> getter, std::function<void(underlying)> setter) :
getter(getter), setter(setter) {}
std::function<underlying()> getter;
std::function<void(underlying)> setter;
};
#define BITFIELD_REF(s,m) bitfield_ref<decltype(s.m)>( \
[&s]() { return s.m; }, \
[&s](decltype(s.m) v) { s.m = v; })
它可以这样使用
struct moo
{
unsigned int a : 2;
unsigned int b : 3;
};
unsigned int test(bitfield_ref<unsigned int> x)
{
x.set(3);
return x.get() + 1;
}
int main()
{
moo m;
std::cout << test(BITFIELD_REF(m, a)) << "\n";
}
还有可能摆脱
get
和
set
通过定义转换运算符和赋值运算符(以及与之相关的所有复合赋值),为了简洁起见,省略了这一点。