c++ - union 中的 boost::optional<>?

标签 c++ boost optional-variables

我有一个可选的 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/

相关文章:

c++ - C++ 中的头文件和命名空间

c++ - 类型转换成员函数指针

c++ - 查找批号是否在多个间隔中的最快方法

python - Boost.Python 和 C++ std::vector of pointers

c++ - 在类 : scoped_ptr or shared_ptr? 中将智能指针作为参数传递

ios - Swift:为什么我所有的可选变量看起来像 "Optional(305.502)"

c++ - 如何根据 boost 版本有选择地包含 boost header

c++ - 在构造函数中初始化 Boost shared_ptr

swift - Swift 中的可选链接或三元表达式?

swift - Swift 中两种可选语法的区别