C++

列挙型のサブカテゴリをvariantで作ろう

列挙型のサブカテゴリをvariantで作ろう

目的

c++で列挙型を使っていると列挙しているものが増えてきて 管理に苦しむことはないだろうか。 そこで増えてきた要素をカテゴライズできるサブグループをvariantを使い、 分類する方法を記載する。

nlohmann Jsonのcmake設定

はじめに

C++でJsonを読み書きするライブラリであるnlohmann-jsonを cmakeで取り込む方法を記載する。

方法

基本的にnlohmann-jsonのreadmeに 書かれている通りに記載する。 ただし、そのままではnlohmann/json.hppで取り込めないためinclude_directoriesで ヘッダーファイルの場所を指定する。

# use FetchContent to download
include(FetchContent)

# fetch library
FetchContent_Declare(json URL https://github.com/nlohmann/json/releases/download/v3.11.3/json.tar.xz)
FetchContent_MakeAvailable(json)
include_directories(${json_SOURCE_DIR}/include) # append to include header

# link
target_include_directories(hoge PUBLIC nlohmann_json::nlohmann_json)

すると次のようにインクルードできる。

#include <nlohmann/json.hpp>

Magic EnumをCmakeに取り込む方法

はじめに

magic-enumは、header onlyで動くc++の標準では手が届かないenumの機能に 関するライブラリです。 magic-enumを使うことで明らかに自明なenumから文字列、 文字列からenumといった変換が可能になります。

debian系の環境ならaptで導入することもできますが、 windows環境ではvcpkgやconanを使うなどの方法もありますが、 導入が面倒です。

そこでビルドに使うcmakeを用いてfetchして 組み込んでしまおうというアイディアです。

方法

cmakeのスプリクトに次のような記述をします。

include(FetchContent)
FetchContent_Populate(
  magic_enum
  URL https://github.com/Neargye/magic_enum/releases/download/v0.9.7/magic_enum-v0.9.7.tar.gz
)
include_directories(${magic_enum_SOURCE_DIR}/include)

すると#include<magic_enum/magic_enum.hpp>で取り込めるようになります。