递归变体容器编译器错误

recursive variant container compiler error

本文关键字:编译器 错误 递归      更新时间:2023-10-16

我希望变体包含其类型的对象的副本。不知何故它不起作用:

struct value
{
};
class json;
using json = ::boost::variant<
  ::std::vector<::std::unique_ptr<json> >,
  ::std::unordered_map<::std::string, ::std::unique_ptr<json> >,
  value
>;
json.hpp:116:2: error: conflicting declaration 'using json = '
 >;
  ^
json.hpp:110:7: error: 'class json' has a previous declaration as 'class json'
 class json;

我已经知道 2 种解决方法:::std::unique_ptr<void> ,带有自定义删除器,以及使用 ::boost::any 代替变体的可能性,但这些是唯一的方法吗?::boost::any的问题在于我需要启用RTTI才能使其工作。

怎么样:

struct json : ::boost::variant<
  ::std::vector<::std::unique_ptr<json> >,
  ::std::unordered_map<::std::string, ::std::unique_ptr<json> >,
  value
>
{
  using variant::variant;
  template <typename U>
  json& operator=(U&& u)
  {
    variant::operator=(::std::forward<U>(u));
    return *this;
  }
};

这将是解决方案,除了它不适用于 g++(由于构造函数调用不明确,从向量构造 json 失败)。从常量引用构造到这样的向量有效,但不能从非常量引用构造。我不知道为什么。此外,unique_ptr对我来说不适用于boost::variant,因为它是不可复制的(shared_ptr确实有效)。