错误:多个成员的初始化
我正在尝试创建一个 constexpr 联合,根据模板参数设置其值的最后 3 位。这个想法是,构造函数首先将 val
变量初始化为传递给构造函数的任何内容,然后使用模板参数和位字段设置最后三位。然而,编译器正在抱怨。
我的代码:
template<typename T, bool a, bool b, bool c>
union some_type
{
T val;
struct {
T empty_ : sizeof(T)*CHAR_BIT-3;
T a_ : 1;
T b_ : 1;
T c_ : 1;
} bit_type;
some_type(uint32_t var) : val{var}, bit_type{0,a,b,c} {}
};
int main()
{
some_type<uint32_t,1,1,0>(245878);
}
错误:
<source>:244:37: required from here
<source>:234:5: error: initializations for multiple members of 'some_type<unsigned int, true, true, false>'
234 | some_type(uint32_t var) : type{var}, bit_type{0,a,b,c} {}
| ^~~~~~~~~
有什么办法我可以以 constexpr 方式设置值的最后三位并保留存储哪些位的信息(在上面的示例中)通过命名位 a_、b_、c_ 以便以后的读取操作)?
I'm trying to create a constexpr union that sets the last 3 bits of its value according to template parameters. The idea is that the constructor first initializes the val
variable to whatever is passed to the constructor and then the last three bits are set with template parameters and a bitfield. However, the compiler is complaining.
My code:
template<typename T, bool a, bool b, bool c>
union some_type
{
T val;
struct {
T empty_ : sizeof(T)*CHAR_BIT-3;
T a_ : 1;
T b_ : 1;
T c_ : 1;
} bit_type;
some_type(uint32_t var) : val{var}, bit_type{0,a,b,c} {}
};
int main()
{
some_type<uint32_t,1,1,0>(245878);
}
Error:
<source>:244:37: required from here
<source>:234:5: error: initializations for multiple members of 'some_type<unsigned int, true, true, false>'
234 | some_type(uint32_t var) : type{var}, bit_type{0,a,b,c} {}
| ^~~~~~~~~
Is there someway I can set the last three bits of a value in a constexpr way AND perserve the information of which bits were stored (in the above example by naming the bits a_, b_, c_ for later read operations)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论