Shamrock 2025.10.0
Astrophysical Code
Loading...
Searching...
No Matches
json_variant.hpp
Go to the documentation of this file.
1// -------------------------------------------------------//
2//
3// SHAMROCK code for hydrodynamics
4// Copyright (c) 2021-2026 Timothée David--Cléris <tim.shamrock@proton.me>
5// SPDX-License-Identifier: CeCILL Free Software License Agreement v2.1
6// Shamrock is licensed under the CeCILL 2.1 License, see LICENSE for more information
7//
8// -------------------------------------------------------//
9
10#pragma once
11
20#include "shambase/string.hpp"
21#include <nlohmann/json.hpp>
22#include <variant>
23
24namespace shamrock {
25 // Primary template (undefined for non-variant types)
26 template<typename T>
28
29 // Specialization for std::variant
30 template<typename... Ts>
31 struct variant_to_tuple<std::variant<Ts...>> {
32 using type = std::tuple<Ts...>;
33 };
34
35 // Helper alias
36 template<typename T>
37 using variant_to_tuple_t = typename variant_to_tuple<T>::type;
38
39 template<class T>
40 struct type_tag {
41 using type = T;
42 };
43
44 template<class Functor, typename... Ts>
45 inline bool on_variant_match(
46 const std::string &type_id, Functor &&callback, const std::variant<Ts...> &var) {
47 bool matched = false;
48
49 (
50 [&] {
51 if (!matched && type_id == Ts::variant_type_name) {
52 callback(type_tag<Ts>{});
53 matched = true;
54 }
55 }(),
56 ...);
57
58 return matched;
59 }
60
61 template<class Functor, typename... Ts>
62 inline void on_variant_cases(Functor &&callback, const std::variant<Ts...> &var) {
63
64 (
65 [&] {
66 callback(type_tag<Ts>{});
67 }(),
68 ...);
69 }
70
71 template<typename... Ts>
72 inline void json_deserialize_variant(
73 const nlohmann::json &j, const std::string &type_id, std::variant<Ts...> &var) {
74
75 bool matched = on_variant_match(
76 type_id,
77 [&](auto tag) {
78 using Talt = typename decltype(tag)::type;
79 var = std::variant<Ts...>{j.get<Talt>()};
80 },
81 var);
82
83 if (!matched) {
84 std::vector<std::string> available_types;
85 on_variant_cases(
86 [&](auto tag) {
87 using Talt = typename decltype(tag)::type;
88 available_types.push_back(std::string(Talt::variant_type_name));
89 },
90 var);
91
93 "unknown type: {}\navailable types: {}\njson: {}",
94 type_id,
95 available_types,
96 j.dump(4)));
97 }
98 }
99
100} // namespace shamrock
This header file contains utility functions related to exception handling in the code.
void throw_with_loc(std::string message, SourceLocation loc=SourceLocation{})
Throw an exception and append the source location to it.
namespace for the main framework
Definition __init__.py:1
STL namespace.