我有一个可选的 POD 结构,它将包含在 union 中。
boost::optional<>
按值保留其类型,所以我认为这可行:
union helper
{
int foo;
struct
{
char basic_info;
struct details {
//...
};
boost::optional<details> extended_info;
} bar;
// ...
};
helper x = make_bar();
if( x.bar.extended_info )
{
// use x.bar.extended_info->elements
}
但是 VS2008 提示我的 bar
现在结构had a copy constructor由于 boost::optional<details>
元素。
作为替代,我添加了一个 bool 标志来指示可选参数是否有效,但它很笨重:
union helper
{
int foo;
struct
{
char basic;
struct details {
bool valid;
//...
} extended;
} bar;
// ...
};
我考虑实现 details::operator bool()
返回 details::valid
变量,但这是晦涩的,对人类有害。
boost::optional<>
清楚地记录语法和意图,不需要侦探工作。
最后,helper
union 需要是 POD,所以我不能做任何动态分配 - 否则我会使用指针。
对语法上类似于 boost::optional<>
的任何建议这在 union 中可用吗?
最佳答案
您不能将非 POD 类型用作 union 中的字段。在 C++ 中使用 boost::variant 或类似的东西而不是 union 。保留 union 只是为了与用 C 编写的模块兼容。
关于c++ - union 中的 boost::optional<>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4673932/