我有一个类型 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/