$darkmode
with_std.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  */
26 #pragma once
27 #ifndef FABLE_JSON_WITH_STD_HPP_
28 #define FABLE_JSON_WITH_STD_HPP_
29 
30 #include <memory> // for unique_ptr<>, shared_ptr<>, weak_ptr<>
31 
32 #include <nlohmann/json.hpp>
33 
34 /*
35  * In order to provide serialization for third-party types, we need to either
36  * use their namespace or provide a specialization in that of nlohmann. It is
37  * illegal to define anything in the std namespace, so we are left no choice in
38  * this regard.
39  *
40  * See: https://github.com/nlohmann/json
41  */
42 namespace nlohmann {
43 
44 template <typename T>
45 struct adl_serializer<std::unique_ptr<T>> {
46  static void to_json(json& j, const std::unique_ptr<T>& opt) {
47  if (opt) {
48  j = *opt;
49  } else {
50  j = nullptr;
51  }
52  }
53 };
54 
55 template <typename T>
56 struct adl_serializer<std::shared_ptr<T>> {
57  static void to_json(json& j, const std::shared_ptr<T>& opt) {
58  if (opt) {
59  j = *opt;
60  } else {
61  j = nullptr;
62  }
63  }
64 };
65 
66 template <typename T>
67 struct adl_serializer<std::weak_ptr<T>> {
68  static void to_json(json& j, const std::weak_ptr<T>& opt) {
69  auto ptr = opt.lock();
70  if (ptr) {
71  j = *ptr;
72  } else {
73  j = nullptr;
74  }
75  }
76 };
77 
78 } // namespace nlohmann
79 
80 #endif // FABLE_JSON_WITH_STD_HPP_
Definition: confable.hpp:132