diff --git a/libsrc/core/archive.hpp b/libsrc/core/archive.hpp index 0e5d69bc..4d72e826 100644 --- a/libsrc/core/archive.hpp +++ b/libsrc/core/archive.hpp @@ -9,6 +9,7 @@ #include // for function #include // for map #include // for shared_ptr +#include // for optional #include // for string #include // for declval, enable_if_t, false_type, is_co... #include // for std::byte @@ -290,6 +291,24 @@ namespace ngcore } return (*this); } + template + Archive& operator& (std::optional& opt) + { + bool has_value = opt.has_value(); + (*this) & has_value; + if(has_value) + { + if(Output()) + (*this) << *opt; + else + { + T value; + (*this) & value; + opt = value; + } + } + return (*this); + } // Archive arrays ===================================================== // this functions can be overloaded in Archive implementations for more efficiency template >> diff --git a/tests/catch/archive.cpp b/tests/catch/archive.cpp index 8d7a413c..8c436697 100644 --- a/tests/catch/archive.cpp +++ b/tests/catch/archive.cpp @@ -265,6 +265,28 @@ void testEnum(Archive& in, Archive& out) CHECK(enin == CASE2); } +void testOptional(Archive& in, Archive& out) + { + { + std::optional no_value; + std::optional myint = 42; + std::optional mystr = "have an optional string"; + out & no_value & myint & mystr; + out.FlushBuffer(); + } + { + std::optional no_value_; + std::optional myint_; + std::optional mystr_; + in & no_value_ & myint_ & mystr_; + CHECK(no_value_.has_value() == false); + CHECK(myint_.has_value() == true); + CHECK(*myint_ == 42); + CHECK(mystr_.has_value() == true); + CHECK(*mystr_ == "have an optional string"); + } + } + void testArchive(Archive& in, Archive& out) { SECTION("Empty String") @@ -322,6 +344,10 @@ void testArchive(Archive& in, Archive& out) { testEnum(in, out); } + SECTION("optional") + { + testOptional(in, out); + } } TEST_CASE("BinaryArchive")