c++ - 具有不可移动类型的 boost::variant

标签 c++ boost boost-variant

我有一个类型 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());

最佳答案

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

BoundedType

The requirements on a bounded type are as follows:

CopyConstructible or MoveConstructible.

Destructor upholds the no-throw exception-safety guarantee.

Complete at the point of variant template instantiation. (See boost::recursive_wrapper for a type wrapper that accepts incomplete types to enable recursive variant types.)

Every type specified as a template argument to variant must at minimum fulfill the above requirements. In addition, certain features of variant are available only if its bounded types meet the requirements of these following additional concepts... (etc.)

所以看起来您需要存储一个引用,或者更可能是一个 std::unique_ptr<T>在变体中(或封装智能指针的 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"));

关于c++ - 具有不可移动类型的 boost::variant,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36374731/

相关文章:

c++ - 使用 Boost.Log 和 Boost.ASIO 导致崩溃

c++ - Boost::Array 中的垃圾值与 Boost::Asio 一起使用

c++ - 你如何在C++中将两个字符串写入一个文件

c++ - 需要帮助才能进入 ifstream::open 以打开文件并从中获取行

c++ - while 循环和 getchar()

c++ - 如何制作适用于 gcc 4.6 的递归 boost::variant?

c++ - boost 变体 istringstream 和流错误

c++ - 构造一个包含变量类型索引中第 n 类型值的 boost 变量?

c++ - 通用重载运算符

c++ - 如何检测是否安装了自定义 terminate() 处理程序?