c++ - 递归变量容器编译器错误

标签 c++ c++11 variant

我想要一个包含其类型对象拷贝的变体。不知何故它不起作用:

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++ 不起作用(由于构造函数调用不明确,从 vector 构造 json 失败)。从 const 引用 到这样的 vector 的构造是有效的,但不是从非常量引用构造的。我不知道为什么。此外,unique_ptr 对我来说不适用于 boost::variant,因为它不可复制(shared_ptr 确实有效)。

关于c++ - 递归变量容器编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21850563/

相关文章:

c++ - 简单 C++ 代码中的段错误

c++ - 使用 std::bind 的功能组合

delphi - 测试强制转换 OleVariant 是否会引发异常(不引发异常)

c++ - 如何将自定义结构传递到 C++(非 CLI)中的 _variant_t?

C++ 静态友元方法示例(需要说明)

c++ - 如何知道从二进制文件中读取的记录是否有空字段? C++

c++ - 想要更新结果

c++ - Boost 记录器链接问题

c++ - 运行时类型检查

c++ - 从 boost::variant 按索引获取项目,就像使用 std::variant 一样