camcom 1.0.3
 
Loading...
Searching...
No Matches
value.hpp
Go to the documentation of this file.
1
8
9#ifndef CAMCOM_COMMON_VALUE_HPP
10#define CAMCOM_COMMON_VALUE_HPP
11
12#include <variant>
13#include <string>
14#include <fmt/format.h>
15
16namespace camcom::common {
17 using Value = std::variant<int, float, double, std::string, bool>;
18
19 inline std::string_view ValueTypeString(const Value &v) noexcept {
20 return std::visit([](const auto &x) -> std::string_view {
21 using T = std::decay_t<decltype(x)>;
22 if constexpr (std::is_same_v<T, int>) { return "int"; }
23 else if constexpr (std::is_same_v<T, float>) { return "float"; }
24 else if constexpr (std::is_same_v<T, double>) { return "double"; }
25 else if constexpr (std::is_same_v<T, std::string>) { return "string"; }
26 else if constexpr (std::is_same_v<T, bool>) { return "bool"; }
27 else { return "unknown"; }
28 }, v);
29 }
30
31} // namespace camcom::common
32
33// ---- fmt support for camcom::common::Value ----
34namespace fmt {
35
36 template <>
37 struct formatter<camcom::common::Value> {
38 // store any specs after the colon, e.g. ".3f", ">10", etc.
39 std::string specs;
40
41 // parse optional format specs for the held type
42 constexpr auto parse(format_parse_context& ctx) {
43 auto it = ctx.begin();
44 const auto end = ctx.end();
45 if (it != end && *it != '}') {
46 const auto start = it;
47 do { ++it; } while (it != end && *it != '}');
48 specs.assign(start, it); // everything between ':' and '}'
49 }
50 return it; // return past-the-end of the parsed range
51 }
52
53 template <typename FormatContext>
54 auto format(const camcom::common::Value& v, FormatContext& ctx) const
55 -> typename FormatContext::iterator
56 {
57 return std::visit([&](const auto& x) -> typename FormatContext::iterator {
58 if (specs.empty()) {
59 // no specs -> just "{}"
60 return fmt::format_to(ctx.out(), "{}", x);
61 } else {
62 // build "{:<specs>}" dynamically; must use fmt::runtime
63 std::string f;
64 f.reserve(specs.size() + 3);
65 f += "{:";
66 f += specs;
67 f += '}';
68 return fmt::format_to(ctx.out(), fmt::runtime(f), x);
69 }
70 }, v);
71 }
72 };
73
74} // namespace fmt
75
76#endif // CAMCOM_COMMON_VALUE_HPP
Definition adapterBase.cpp:18
std::variant< int, float, double, std::string, bool > Value
Definition value.hpp:17
std::string_view ValueTypeString(const Value &v) noexcept
Definition value.hpp:19
Definition adapterBase.cpp:18
Definition value.hpp:34
constexpr auto parse(format_parse_context &ctx)
Definition value.hpp:42
auto format(const camcom::common::Value &v, FormatContext &ctx) const -> typename FormatContext::iterator
Definition value.hpp:54
std::string specs
Definition value.hpp:39