JSON Voorhees
Killer JSON for C++
Loading...
Searching...
No Matches
optional_adapter.hpp
Go to the documentation of this file.
1/// \file jsonv/serialization/optional_adapter.hpp
2///
3/// Copyright (c) 2017-2020 by Travis Gockel. All rights reserved.
4///
5/// This program is free software: you can redistribute it and/or modify it under the terms of the Apache License
6/// as published by the Apache Software Foundation, either version 2 of the License, or (at your option) any later
7/// version.
8///
9/// \author Travis Gockel (travis@gockelhut.com)
10#pragma once
11
12#include <jsonv/config.hpp>
14
15#include "adapter_for.hpp"
16
17namespace jsonv
18{
19
20/// \addtogroup Serialization
21/// \{
22
23/// An adapter for optional-like types. This is for convenience of creating an \c adapter for things like
24/// \c std::optional or \c boost::optional.
25///
26/// \tparam TOptional The optional container type. It must have a member type named \c value_type which holds the
27/// actual type. It must default-construct to the "none" type and have a single-argument constructor which takes a
28/// \c TOptional::value_type. It must support a boolean conversion operator for checking if the value is none and a
29/// unary \c operator* for getting the underlying value. Both \c std::optional and \c boost::optional possess all of
30/// these properties.
31template <typename TOptional>
33 public adapter_for<TOptional>
34{
35 using element_type = typename TOptional::value_type;
36
37protected:
38 virtual TOptional create(const extraction_context& context, const value& from) const override
39 {
40 if (from.is_null())
41 return TOptional();
42 else
43 return TOptional(context.extract<element_type>(from));
44 }
45
46 virtual value to_json(const serialization_context& context, const TOptional& from) const override
47 {
48 if (from)
49 return context.to_json(*from);
50 else
51 return value();
52 }
53};
54
55/// \}
56
57}
An adapter for the type T.
virtual void extract(const extraction_context &context, const value &from, void *into) const override
Extract a the type from a value into a region of memory.
An adapter for enumeration types.
An adapter for optional-like types.
Represents a single JSON value, which can be any one of a potential kind, each behaving slightly diff...
Definition value.hpp:107
Copyright (c) 2014-2020 by Travis Gockel.
Conversion between C++ types and JSON values.