archive optional<T>

This commit is contained in:
mhochsteger@cerbsim.com 2021-11-10 12:08:56 +01:00
parent 2724317985
commit f95332d0a1
2 changed files with 45 additions and 0 deletions

View File

@ -9,6 +9,7 @@
#include <functional> // for function
#include <map> // for map
#include <memory> // for shared_ptr
#include <optional> // for optional
#include <string> // for string
#include <type_traits> // for declval, enable_if_t, false_type, is_co...
#include <cstddef> // for std::byte
@ -290,6 +291,24 @@ namespace ngcore
}
return (*this);
}
template<typename T>
Archive& operator& (std::optional<T>& 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 <typename T, typename = std::enable_if_t<is_archivable<T>>>

View File

@ -265,6 +265,28 @@ void testEnum(Archive& in, Archive& out)
CHECK(enin == CASE2);
}
void testOptional(Archive& in, Archive& out)
{
{
std::optional<int> no_value;
std::optional<int> myint = 42;
std::optional<string> mystr = "have an optional string";
out & no_value & myint & mystr;
out.FlushBuffer();
}
{
std::optional<int> no_value_;
std::optional<int> myint_;
std::optional<string> 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")