$darkmode
boost_optional.hpp
Go to the documentation of this file.
1 /*
2  * Copyright 2020 Robert Bosch GmbH
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  * SPDX-License-Identifier: Apache-2.0
17  */
25 #pragma once
26 
27 #include <boost/optional.hpp> // for optional<>
28 #include <nlohmann/json.hpp> // for adl_serializer<>, json
29 
30 /*
31  * In order to provide serialization for third-party types, we need to either
32  * use their namespace or provide a specialization in that of nlohmann. It is
33  * illegal to define anything in the std namespace, so we are left no choice in
34  * this regard.
35  *
36  * See: https://github.com/nlohmann/json
37  */
38 namespace nlohmann {
39 
40 template <typename T>
41 struct adl_serializer<boost::optional<T>> {
42  static void to_json(json& j, const boost::optional<T>& opt) {
43  if (opt) {
44  j = *opt;
45  } else {
46  j = nullptr;
47  }
48  }
49 
50  static void from_json(const json& j, boost::optional<T>& opt) {
51  if (j.type() == json::value_t::null) {
52  opt.reset();
53  } else {
54  *opt = j.get<T>();
55  }
56  }
57 };
58 
59 } // namespace nlohmann