https://github.com/avakar/destructure
Structure to Tuple Conversions in C++17
https://github.com/avakar/destructure
cpp cpp17
Last synced: about 2 months ago
JSON representation
Structure to Tuple Conversions in C++17
- Host: GitHub
- URL: https://github.com/avakar/destructure
- Owner: avakar
- License: mit
- Created: 2019-12-01T22:26:57.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2019-12-06T18:52:42.000Z (over 5 years ago)
- Last Synced: 2025-03-22T15:02:21.524Z (2 months ago)
- Topics: cpp, cpp17
- Language: C++
- Homepage:
- Size: 5.86 KB
- Stars: 25
- Watchers: 2
- Forks: 2
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Structure to Tuple Conversions in C++17
This single-header library provides the following pair of functions.
template
auto destructure(T & val)
{
auto && [an...] = std::forward(val);
return std::tie(an...);
}template
auto destructure(T && val)
{
auto && [an...] = std::forward(val);
return std::tuple(std::move(an)...);
}Unfortunately, there are no variadic structured bindings in C++17,
so the implementation is a bit more involved.## Getting Started
Either use the CMakeFile in the repo or simply copy `destructure.h`
to your project. Then include it.#include
using avakar::destructure;Now, consider the following structure.
struct X
{
int a;
std::string b;
};The `destructure` function will turn an object of type `X` into a tuple
of `int` and `std::string`.X x;
auto tied = destructure(x);
static_assert(std::is_same_v>);Notice that for an l-value, destructuring results in a tuple
of references. You can modify the object `x` via the tuple.std::get<0>(tied) = 1;
assert(x.a == 1);For an r-value, `destructure` returns a tuple of values.
auto tup = destructure(X{1, "test"});
static_assert(std::is_same_v>);## Limitations
The library only supports structures of up to 64 members by default,
although you can generate your own version of the header with
the following command../src/generate.py -n 100
This will output a new header file containing the function
in the `destructure_100` namespace. Use `--inline` to make the namespace
inline.