Skip to content

Commit

Permalink
feat: json::value 支持直接通过 array/object 的可构造参数构造
Browse files Browse the repository at this point in the history
  • Loading branch information
MistEO committed Oct 16, 2023
1 parent 977dcc4 commit 99eb9d7
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 7 deletions.
26 changes: 22 additions & 4 deletions include/json.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -92,14 +92,13 @@ class basic_value
basic_value(basic_object<string_t> obj);
basic_value(std::initializer_list<std::pair<string_t, basic_value<string_t>>> init_list);

template <typename value_t>
basic_value(value_t&& val);

// Constructed from raw data
template <typename... args_t>
basic_value(value_type type, args_t&&... args);

// Prohibit conversion of other types to basic_value
template <typename value_t>
basic_value(value_t) = delete;

~basic_value();

bool valid() const noexcept { return _type != value_type::invalid; }
Expand Down Expand Up @@ -708,6 +707,25 @@ MEOJSON_INLINE basic_value<string_t>::basic_value(
;
}

template <typename string_t>
template <typename value_t>
MEOJSON_INLINE basic_value<string_t>::basic_value(value_t&& val)
{
constexpr bool is_array_val = std::is_constructible_v<basic_array<string_t>, value_t>;
constexpr bool is_object_val = std::is_constructible_v<basic_object<string_t>, value_t>;

static_assert(is_array_val || is_object_val, "value can not constructure a array or object");

if constexpr (is_array_val) {
_type = value_type::array;
_raw_data = std::make_unique<basic_array<string_t>>(std::forward<value_t>(val));
}
else if constexpr (is_object_val) {
_type = value_type::object;
_raw_data = std::make_unique<basic_object<string_t>>(std::forward<value_t>(val));
}
}

// for Pimpl
template <typename string_t>
MEOJSON_INLINE basic_value<string_t>::~basic_value() = default;
Expand Down
6 changes: 3 additions & 3 deletions sample/sample.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -227,16 +227,16 @@ bool serializing()
root["arr"] += json::array { 6, 7 };

std::vector<int> vec = { 1, 2, 3, 4, 5 };
root["arr from vec"] = json::array(vec);
root["arr from vec"] = vec;

std::set<std::string> set = { "a", "bb\n\nb", "cc\t" };
root["arr from set"] = json::array(set);
root["arr from set"] = set;

std::map<std::string, int> map {
{ "key1", 1 },
{ "key2", 2 },
};
root["obj from map"] = json::object(map);
root["obj from map"] = map;

std::vector<std::list<std::set<int>>> complex { { { 1, 2, 3 }, { 4, 5 } }, { { 6 }, { 7, 8 } } };
root["complex"] = json::serialize<false>(complex);
Expand Down

0 comments on commit 99eb9d7

Please sign in to comment.