Skip to content

Commit 721dc36

Browse files
committed
Added support for optionals.
1 parent be49adf commit 721dc36

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

include/json5/json5_reflect.hpp

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,12 @@ template <typename T> error from_file( std::string_view fileName, T &out );
3737

3838
namespace detail {
3939

40+
template <typename T> struct is_optional : public std::false_type { };
41+
42+
template <typename T> struct is_optional<std::optional<T>> : public std::true_type { };
43+
44+
template <typename T> constexpr static bool is_optional_v = is_optional<T>::value;
45+
4046
// Pre-declare so compiler knows it exists before it is attempted to be used
4147
template <typename T> error read(const json5::value& in, T& out);
4248

@@ -153,7 +159,12 @@ inline json5::value write_enum( writer &w, T in )
153159
template <typename Type>
154160
inline void write_tuple_value(writer& w, std::string_view name, const Type& in)
155161
{
156-
if constexpr ( std::is_enum_v<Type> )
162+
if constexpr (is_optional_v<Type>)
163+
{
164+
if (in)
165+
write_tuple_value<typename Type::value_type>(w, name, *in);
166+
}
167+
else if constexpr (std::is_enum_v<Type>)
157168
{
158169
if constexpr ( enum_table<Type>() )
159170
w[name] = write_enum( w, in );
@@ -360,7 +371,13 @@ inline error read_enum( const json5::value &in, T &out )
360371
template <typename Type>
361372
inline error read_tuple_value( const json5::object_view::iterator iter, Type &out )
362373
{
363-
if constexpr ( std::is_enum_v<Type> )
374+
if constexpr (is_optional_v<Type>)
375+
{
376+
out = typename Type::value_type();
377+
if (auto err = read_tuple_value<typename Type::value_type>(iter, *out))
378+
return err;
379+
}
380+
else if constexpr (std::is_enum_v<Type>)
364381
{
365382
if constexpr ( enum_table<Type>() )
366383
{

0 commit comments

Comments
 (0)