LoginSignup
5

More than 5 years have passed since last update.

cereal と boost::variant で何でもほいほい入れてシリアライズする例

Posted at

概要

今朝ほど boostjp の boost::variant に boost::make_recursive_variant の例を書きました。また、今日は日中にお仕事でも cereal を便利に使ってにゃんにゃんシリアライズしていました。

と、いうわけで、 boost::variantcereal を使い、「何でもほいほい入れてシリアライズできちゃう素敵かもしれない何か」の実装例を紹介したいと思います。

#include <cereal/cereal.hpp>
#include <cereal/archives/json.hpp>
#include <cereal/types/vector.hpp>
#include <cereal/types/unordered_map.hpp>
#include <cereal/types/string.hpp>
#include <cereal/types/boost_variant.hpp>

using variant_data_type = boost::make_recursive_variant
< std::string
, std::uint8_t, std::uint16_t, std::uint32_t, std::uint64_t
, std::int8_t, std::int16_t, std::int32_t, std::int64_t
, float, double, long double
, bool
, std::vector< boost::recursive_variant_ >
, std::unordered_map< std::string, boost::recursive_variant_ >
>::type;

using variant_array_type = std::vector< variant_data_type >;
using variant_map_type   = std::unordered_map< std::string, variant_data_type >;

auto main() -> int
{
  using namespace std::literals::string_literals;

  variant_array_type array{ "hoge"s, true, false, 0x12345678 };
  variant_map_type   map{ { "key-1"s, "value"s }, { "key-2"s, 3.14f }, { "key-3"s, array } };
  variant_data_type  data = map;
  cereal::JSONOutputArchive( std::cout )( data );
}

出力

{
    "value0": {
        "which": 14,
        "data": [
            {
                "key": "key-3",
                "value": {
                    "which": 13,
                    "data": [
                        {
                            "which": 0,
                            "data": "hoge"
                        },
                        {
                            "which": 12,
                            "data": true
                        },
                        {
                            "which": 12,
                            "data": false
                        },
                        {
                            "which": 7,
                            "data": 305419896
                        }
                    ]
                }
            },
            {
                "key": "key-1",
                "value": {
                    "which": 0,
                    "data": "value"
                }
            },
            {
                "key": "key-2",
                "value": {
                    "which": 9,
                    "data": 3.1400001049041748
                }
            }
        ]
    }
}

所感

( ゚∀゚)アハハ八八ノヽノヽノヽノ \ / \/ \

・・・ほとんどわたし何もコード書いてなくてなぜかあやまりたくなるほど快適に素敵ななんでもほいほいを実装できてしまいました。快適。

Reference

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5