gpt4 book ai didi

c++ - 如何通过引用传递位域

转载 作者:行者123 更新时间:2023-12-03 07:00:33 24 4
gpt4 key购买 nike

请注意,已经存在具有几乎完全相同标题的问题,但提出了一个非常不同的问题。
假设我想要一个将位域引用或指针作为参数的方法。这不合法,但也许一个例子可以澄清:

class Foo {

unsigned a:2, b:2, c:2;

bool Bar( unsigned* px:2 ) { *px = a; return true; };
}

Foo foo;
if ( foo.Bar( &foo.b ) )
exit( EXIT_SUCCESS );
我可以把 Bar 写成一个宏:
#define BAR( pfoo, field ) ( ( (pfoo)->field = (pfoo)->a ), true )

Foo foo;
if ( BAR( &foo, b ) )
exit( EXIT_SUCCESS );
许多您在 C 中编写此类宏的地方现在可以使用函数模板来处理。是否有模板解决方案可以在 C++11 或更高版本中合法地编写上述 Bar() 方法?

最佳答案

有可能以一种相当低效和迂回的方式拼凑出一些充当位域引用的东西。

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";
}
还可以摆脱 getset通过定义一个转换运算符和一个赋值运算符(以及所有与之配套的复合赋值),为简洁起见省略了这一点。

关于c++ - 如何通过引用传递位域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64347614/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com