mirror of
https://github.com/nlohmann/json.git
synced 2025-07-28 12:02:00 +03:00
Documentation change (#3672)
Co-authored-by: Florian Albrechtskirchinger <falbrechtskirchinger@gmail.com>
This commit is contained in:
33
docs/examples/nlohmann_json_namespace_begin.c++17.cpp
Normal file
33
docs/examples/nlohmann_json_namespace_begin.c++17.cpp
Normal file
@ -0,0 +1,33 @@
|
||||
#include <iostream>
|
||||
#include <optional>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
// partial specialization (see https://json.nlohmann.me/features/arbitrary_types/)
|
||||
NLOHMANN_JSON_NAMESPACE_BEGIN
|
||||
template <typename T>
|
||||
struct adl_serializer<std::optional<T>>
|
||||
{
|
||||
static void to_json(json& j, const std::optional<T>& opt)
|
||||
{
|
||||
if (opt == std::nullopt)
|
||||
{
|
||||
j = nullptr;
|
||||
}
|
||||
else
|
||||
{
|
||||
j = *opt;
|
||||
}
|
||||
}
|
||||
};
|
||||
NLOHMANN_JSON_NAMESPACE_END
|
||||
|
||||
int main()
|
||||
{
|
||||
std::optional<int> o1 = 1;
|
||||
std::optional<int> o2 = std::nullopt;
|
||||
|
||||
NLOHMANN_JSON_NAMESPACE::json j;
|
||||
j.push_back(o1);
|
||||
j.push_back(o2);
|
||||
std::cout << j << std::endl;
|
||||
}
|
Reference in New Issue
Block a user