错误:多个成员的初始化

发布于 2025-01-14 06:15:09 字数 909 浏览 5 评论 0原文

我正在尝试创建一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文