用于保存JSON的双自递归变量?

问题描述 投票:1回答:1

JSON值可以是字符串,float,bool,null或JSON值的数组或映射。有没有办法在变体中对此递归定义建模?

由于地图和向量的正向声明都相互冲突,因为它们都想知道对方是否是可微毁的,等等。

是否可以通过STL向量和unordered_map类解决此问题?

struct ValueVector;
struct ValueMap;
using Value = std::variant<
    std::monostate, 
    bool, 
    int64_t, 
    double, 
    std::string, 
    ValueVector,
    ValueMap
    >;
namespace std {
  template <> struct hash<ValueVector>
  {
    size_t operator()(const ValueVector& x) const;
  };
  template <> struct hash<ValueMap>
  {
    size_t operator()(const ValueMap& x) const;
  };
  template <> struct is_trivially_destructible<Value> {
    static constexpr bool value = false;
  };
}
struct ValueMap : std::unordered_map<std::string, Value> {};
struct ValueVector : std::vector<Value> {};
c++ variant
1个回答
0
投票

通常来说,您无法定义包含自身的类型;这导致类型不完整。但是,您可以定义一个自身包含pointer的类型。

struct Value {
  std::variant<
    std::monostate, 
    bool, 
    int64_t, 
    double, 
    std::string, 
    std::unordered_map<std::string, Value*>,
    std::vector<Value*>
  > v;
};
© www.soinside.com 2019 - 2024. All rights reserved.