【问题标题】:boost::variant with immovable types具有不可移动类型的 boost::variant
【发布时间】:2016-04-02 14:50:06
【问题描述】:

我有一个不支持移动的类型T

struct T {
    T();
    T(T const&) = delete;
    T& operator=(T const&) = delete;
    T(T&&) = delete;
    T& operator=(T&&) = delete;
};

如何创建boost::variant<T> 类型的对象?以下失败,因为boost::variant<T> 的构造函数显然试图移动参数:

boost::variant<T> x(T());

【问题讨论】:

    标签: c++ boost boost-variant


    【解决方案1】:

    不幸的是,文档说变体的模板参数列表中的任何类型都必须是 BoundedType,其定义如下:

    有界类型

    对有界类型的要求如下:

    CopyConstructible 或 MoveConstructible。

    析构函数支持不抛出异常的安全保证。

    在变体模板实例化点完成。 (有关接受不完整类型以启用递归变体类型的类型包装器,请参见 boost::recursive_wrapper。)

    指定为 variant 的模板参数的每种类型都必须至少满足上述要求。此外,variant 的某些特性只有在其有界类型满足以下这些附加概念的要求时才可用......(等等)

    所以看起来您需要在变体中存储一个引用,或者更可能是一个std::unique_ptr&lt;T&gt;(或者封装智能指针的 T 的一些包装器)。

    类似这样的:

    struct shared_t {
    
        // insert appropriate constructors here, such as:
    
        shared_t(std::string arg1) : _ptr(std::make_shared<T>(std::move(arg1))) 
        {}
    
        operator T&() { return *_ptr; }
        operator const T&() const { return *_ptr; }
    
        std::shared_ptr<T> _ptr;
    };
    
    using my_variant = boost::variant<shared_t, int, double, std::exception_ptr, ...>;
    
    my_variant v(shared_t("foo"));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-11
      • 1970-01-01
      • 2013-08-03
      相关资源
      最近更新 更多