feat: add examples

This commit is contained in:
ToruNiina
2024-06-15 19:23:05 +09:00
parent 7789b4e8be
commit da2a85b500
28 changed files with 954 additions and 0 deletions

1
examples/reflect/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
reflect

View File

@@ -0,0 +1,18 @@
include(FetchContent)
FetchContent_Declare(
boost_ext_reflect
GIT_REPOSITORY https://github.com/boost-ext/reflect
GIT_SHALLOW ON # Download the branch without its history
GIT_TAG v1.1.1
)
FetchContent_MakeAvailable(boost_ext_reflect)
add_executable(reflect reflect.cpp)
target_link_libraries(reflect PRIVATE toml11::toml11)
target_include_directories(reflect PRIVATE
${boost_ext_reflect_SOURCE_DIR}
)
target_compile_features(reflect PRIVATE cxx_std_20)
set_target_properties(reflect PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}")

View File

@@ -0,0 +1,13 @@
# reflect
Auto convert from user-defined `struct`s to `toml::value`.
It depends on [boost-ext/reflect](https://github.com/boost-ext/reflect).
## build
Build toml11 with `-DTOML11_BUILD_EXAMPLES=ON`.
```cpp
$ cmake -B ./build/ -DTOML11_BUILD_EXAMPLES=ON
```

View File

@@ -0,0 +1,38 @@
#include <iostream>
#include <reflect>
#include "reflect.hpp"
struct Hoge
{
int foo;
double bar;
std::string baz;
};
TOML11_REFLECT(Hoge)
int main()
{
toml::value v(toml::table{
{"foo", 42},
{"bar", 3.14},
{"baz", "fuga"},
});
const Hoge h = toml::get<Hoge>(v);
std::cout << "Hoge.foo = " << h.foo << std::endl;
std::cout << "Hoge.bar = " << h.bar << std::endl;
std::cout << "Hoge.baz = " << h.baz << std::endl;
Hoge h2;
h2.foo = 6 * 9;
h2.bar = 2.718;
h2.baz = "piyo";
toml::value v2(h2);
std::cout << toml::format(v2);
return 0;
}

View File

@@ -0,0 +1,61 @@
#ifndef TOML11_REFLECT_HPP
#define TOML11_REFLECT_HPP
#include <reflect> // boost-ext/reflect
#include <toml.hpp>
namespace toml
{
namespace refl
{
template<typename T, typename TC>
T from(const basic_value<TC>& v)
{
T x;
reflect::for_each([&v, &x](auto I) {
using member_type = std::remove_cvref_t<decltype(reflect::get<I>(x))>;
const auto key = std::string(reflect::member_name<I>(x));
reflect::get<I>(x) = toml::find<member_type>(v, key);
}, x);
return x;
}
template<typename TC = toml::type_config, typename T>
basic_value<TC> into(const T& x)
{
basic_value<TC> v(toml::table{});
reflect::for_each([&v, &x](auto I) {
using member_type = std::remove_cvref_t<decltype(reflect::get<I>(x))>;
const auto key = std::string(reflect::member_name<I>(x));
v[key] = reflect::get<I>(x);
}, x);
return v;
}
} // refl
} // toml
#define TOML11_REFLECT(X) \
namespace toml { \
template<> \
struct into<X> \
{ \
template<typename TC = toml::type_config> \
static toml::basic_value<TC> into_toml(const X& x) \
{ \
return refl::into(x); \
} \
}; \
template<> \
struct from<X> \
{ \
template<typename TC = toml::type_config> \
static X from_toml(const toml::basic_value<TC>& v) \
{ \
return refl::from<X>(v); \
} \
}; \
} /* toml */
#endif // TOML11_REFLECT_HPP