加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – …在联合问题中不允许使用构造函数

发布时间:2020-12-16 04:53:57 所属栏目:百科 来源:网络整理
导读:我迫切需要找到解决以下问题的方法: namespace test{ template int param = 0 struct Flags { int _flags; Flags() { _flags = 0; } Flags(int flags) { _flags = flags; } void init() { } }; union example { struct { union { struct { Flags4096 f; }p1
我迫切需要找到解决以下问题的方法:
namespace test
{
    template <int param = 0> struct Flags
    {
        int _flags;

        Flags()
        {
            _flags = 0;
        }

        Flags(int flags)
        {
            _flags = flags;
        }

        void init()
        {

        }
    };

    union example
    {
        struct
        {
            union
            {
                struct
                {
                    Flags<4096> f;
                }p1; //error: member 'test::example::<anonymous struct>::<anonymous union>::<anonymous struct> test::example::<anonymous struct>::<anonymous union>::p1' with constructor not allowed in union

                struct 
                {
                    Flags<16384> ff;
                }p2; //error: member 'test::example::<anonymous struct>::<anonymous union>::<anonymous struct> test::example::<anonymous struct>::<anonymous union>::p2' with constructor not allowed in union
            }parts;

            byte bytes[8];
        }data;

        int data1;
        int data2;
    }
}

令人沮丧的是,如果我将标签添加到p1和p2结构,代码将编译,但f& ff成员无法访问:

...
struct p1
{
    Flags<4096> f;
};

struct p2
{
    Flags<4096> ff;
};
...

void test()
{
    example ex;
    ex.data.bytes[0] = 0; //Ok
    ex.data.parts.p1.f.init(); //error: invalid use of 'struct test::example::<anonymous struct>::<anonymous union>::p1'
}

有什么办法让这项工作以某种方式?

解决方法

正如@Als所说,联盟不能将非POD定义为成员数据,还有一种选择.您仍然可以将指向非POD的指针定义为union的成员数据.

所以这是允许的:

union
{
   struct
   {
      Flags<4096> *pf; //pointer to non-POD
   }p1;
   struct 
   {
      Flags<16384> *pff; //pointer to non-POD
   }p2;
}parts;

但是Boost.Variant是一个更好的选择.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读