CASM  1.1.0
A Clusters Approach to Statistical Mechanics
optional.hh
Go to the documentation of this file.
1 #ifndef CASM_json_optional
2 #define CASM_json_optional
3 
4 namespace CASM {
5 
6 template <typename T>
7 struct jsonConstructor;
8 class jsonParser;
9 
10 template <typename T, typename... Args>
11 jsonParser &to_json(std::optional<T> const &value, jsonParser &json) {
12  if (value.has_value()) {
13  to_json(value.value(), json);
14  } else {
15  json.put_null();
16  }
17  return json;
18 }
19 
20 template <typename T, typename... Args>
21 void from_json(std::optional<T> &value, jsonParser const &json,
22  Args &&... args) {
23  if (json.is_null()) {
24  value.reset();
25  } else {
26  value = jsonConstructor<T>::from_json(json, std::forward<Args>(args)...);
27  }
28 }
29 
31 template <typename T>
32 struct jsonConstructor<std::optional<T>> {
35  template <typename... Args>
36  static std::optional<T> from_json(jsonParser const &json, Args &&... args) {
37  if (json.is_null()) {
38  return std::nullopt;
39  } else {
40  std::optional<T> value =
41  jsonConstructor<T>::from_json(json, std::forward<Args>(args)...);
42  return value;
43  }
44  }
45 };
46 
47 } // namespace CASM
48 
49 #endif
bool is_null() const
Check if null type.
Definition: jsonParser.cc:254
jsonParser & put_null()
Puts 'null' JSON value.
Definition: jsonParser.hh:377
Main CASM namespace.
Definition: APICommand.hh:8
jsonParser & to_json(const ClexDescription &desc, jsonParser &json)
void from_json(ClexDescription &desc, const jsonParser &json)
Definition: stream_io.hh:24
static std::optional< T > from_json(jsonParser const &json, Args &&... args)
Default from_json is equivalent to.
Definition: optional.hh:36
Helper struct for constructing objects that need additional data.
Definition: jsonParser.hh:548
static ReturnType from_json(const jsonParser &json)
Default from_json is equivalent to.
Definition: jsonParser.hh:551