Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/fantasy-peak/yaml_cpp_struct

It's easy to mapping yaml to cpp's struct
https://github.com/fantasy-peak/yaml_cpp_struct

cpp cpp11 cpp17 header-only mapping yaml

Last synced: about 1 month ago
JSON representation

It's easy to mapping yaml to cpp's struct

Awesome Lists containing this project

README

        

# yaml_cpp_struct

[![](https://github.com/fantasy-peak/yaml_cpp_struct/workflows/test/badge.svg)](https://github.com/fantasy-peak/yaml_cpp_struct/actions)

## function

It's a wrapper, It's easy to mapping yaml to cpp's struct

## note

main branch need >= c++17, if you need to use c++11, please use cpp11 branch. cpp11 branch not support std::variant.
Please refer to example for cpp11 branch

## use examples
```
// It relies on two other three open source libraries(yaml-cpp, visit_struct, magic_enum), Please refer to CMakeLists.txt of example
git clone https://github.com/fantasy-peak/yaml_cpp_struct.git
cd ./yaml_cpp_struct/example
mkdir build && cd build
cmake ..
make -j 9
./example ../config.yaml
// use xmake
cd ./yaml_cpp_struct/example
xmake build -v
xmake run example ../../../../config.yaml
```

[Example](./example/main.cpp)
```yaml
---
ch: 'A'
price: 100.05
count: 254
content: "i'm fantasy-peak"
map: { "fantasy": "good", "peak": "good" }
account_info:
flag: false
name: "fantasy-peak"
address: { "127.0.0.1": 8888, "127.0.0.2": 9999 }
msec: 100
tuple: ["fantasy-peak", 89]
map_tuple: {"fantasy-peak": ["map_tuple", 254]}

vec: ["fantasy-001", "fantasy-002"]
set_vec: [9, 5, 7]
account_type: "Personal"
ips: ["127.0.0.1"]
```

```cpp
#include

#include
#include

enum class AccountType : uint8_t {
Personal = 1,
Company = 2,
};
YCS_ADD_ENUM(AccountType, Personal, Company)

std::string to_string(const AccountType& type) {
if (type == AccountType::Personal)
return "Personal";
if (type == AccountType::Company)
return "Company";
throw std::bad_cast();
}

struct AccountInfo {
bool flag;
std::string name;
std::unordered_map address;
std::optional num;
std::chrono::milliseconds msec{100};
std::tuple tuple;
std::unordered_map> map_tuple;
std::string default_str{"hello default"};
std::vector ips;
};
YCS_ADD_STRUCT(AccountInfo, flag, name, address, num, msec, tuple, map_tuple, default_str, ips)

int main(int, char** argv) {
auto [cfg, error] = yaml_cpp_struct::from_yaml(argv[1]);
auto [str, e] = yaml_cpp_struct::to_yaml(cfg.value());
// Load values from environment variables
// export YCS_ENV_IPS=["Google","Runoob","Taobao"]
// auto [cfg, error] = yaml_cpp_struct::from_yaml_env(argv[1], "YCS_ENV_");
return 0;
}
```