boost::variant 具有不可移动的类型
boost::variant with immovable types
我有一个不支持移动的类型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"));
我有一个不支持移动的类型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"));