JSON Voorhees
Killer JSON for C++
Loading...
Searching...
No Matches
function_serializer.hpp
Go to the documentation of this file.
1/// \file jsonv/serialization/function_serializer.hpp
2///
3/// Copyright (c) 2015-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 "serializer_for.hpp"
16
17#include <concepts>
18#include <type_traits>
19#include <utility>
20
21namespace jsonv
22{
23
24/// \addtogroup Serialization
25/// \{
26
27template <typename T, typename FToJson>
29 public serializer_for<T>
30{
31public:
32 // Constrained so that copying from a non-const lvalue reaches the copy constructor, which this would otherwise
33 // beat as the better match.
34 template <typename FUToJson>
35 requires (!std::same_as<std::remove_cvref_t<FUToJson>, function_serializer>)
36 explicit function_serializer(FUToJson&& to_json_) :
37 _to_json(std::forward<FUToJson>(to_json_))
38 { }
39
40protected:
41
43 virtual value to_json(const serialization_context& context, const T& from) const override
44 {
45 return to_json_impl(_to_json, context, from);
46 }
47
48private:
49 template <typename FUToJson>
50 static auto to_json_impl(const FUToJson& func, const serialization_context& context, const T& from)
51 -> decltype(func(context, from))
52 {
53 return func(context, from);
54 }
55
56 template <typename FUToJson, typename = void>
57 static auto to_json_impl(const FUToJson& func, const serialization_context&, const T& from)
58 -> decltype(func(from))
59 {
60 return func(from);
61 }
62
63private:
64 FToJson _to_json;
65};
66
67template <typename T, typename FToJson>
69function_serializer<T, FToJson> make_serializer(FToJson to_json_)
70{
71 return function_serializer<T, FToJson>(std::move(to_json_));
72}
73
74/// \}
75
76}
Provides extra information to routines used for extraction and serialization.
Definition context.hpp:26
Represents a single JSON value, which can be any one of a potential kind, each behaving slightly diff...
Definition value.hpp:113
Copyright (c) 2014-2020 by Travis Gockel.
#define JSONV_NODISCARD
Warn if the caller discards the result of this function.
Definition config.hpp:132
Conversion between C++ types and JSON values.
Copyright (c) 2015-2020 by Travis Gockel.