...与构造函数不允许在联合问题 [英] ... with constructor not allowed in union problem

查看:1199
本文介绍了...与构造函数不允许在联合问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我迫切需要为以下问题找到解决方案:

I desperately need to find a solution for the following problem:

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成员无法访问:


It's frustrating that if I add tags to p1 and p2 structs, the code will compile, but the f & ff members would not be accessible:

...
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'
}



是否有任何方式使这项工作以某种方式?


Is there any way to make this work somehow?

推荐答案

如@Als所说,union不能定义非POD作为成员数据,有一个替代方法。您还可以定义指向非POD的指针作为联合的成员数据。

As @Als said, union cannot define non-POD as member data, there is one alternative. You can still define a pointer to the non-POD as member data of the union.

因此允许这样:

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

但是 Boost.Variant 是更好的选择。

这篇关于...与构造函数不允许在联合问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆