我迫切需要找到以下问题的解决方案:
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所说,union不能将非POD定义为成员数据,有一种替代方法。您仍然可以定义指向非 POD 的指针作为联合的成员数据。
所以这是允许的:
union
{
struct
{
Flags<4096> *pf; //pointer to non-POD
}p1;
struct
{
Flags<16384> *pff; //pointer to non-POD
}p2;
}parts;
但是之后升压变体 http://www.boost.org/doc/libs/1_38_0/doc/html/variant.html是一个更好的选择。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)