Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/nekrolm/better_option
Better implementation of C++ std::optional
https://github.com/nekrolm/better_option
Last synced: 6 days ago
JSON representation
Better implementation of C++ std::optional
- Host: GitHub
- URL: https://github.com/nekrolm/better_option
- Owner: Nekrolm
- License: mit
- Created: 2024-06-30T23:41:47.000Z (7 months ago)
- Default Branch: master
- Last Pushed: 2024-07-29T19:00:18.000Z (6 months ago)
- Last Synced: 2024-11-13T03:14:17.351Z (2 months ago)
- Language: C++
- Size: 65.4 KB
- Stars: 2
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: license.txt
Awesome Lists containing this project
README
# Better Option
This is a small header only library with implementation of C++17 `std::optional`
## Main differences
1. It supports references!. Via custom Ref wrapper. Similar to std::reference_wrapper but simplier
2. It has niche optimization for references: `sizeof(Option>) == sizeof(T*)`
3. It supports `void` via custom `Void` type. We can `.map` with functions returning `void` and also `Option` can be mapped with function accepting no arguments
4. C++20.```C++
using better::None;
using better::Option;
using better::Ref;
using better::Some;int main() {
Option opt = {Some, "hello world"};
auto transformed = std::move(opt)
.map([](auto &&str) { return str.length(); })
.map([](size_t len) { return std::to_string(len); });// can map to void!
auto result = transformed.as_ref().map(
[](const auto &str) { std::cout << *str << "\n"; });// we have niche optimization for references
static_assert(sizeof(transformed.as_ref()) == sizeof(void*));std::cout << "transformed is stil some: " << transformed.is_some() << "\n";
std::string world = "world";
std::cout << result.is_some() << "\n";
static_assert(sizeof(result) == sizeof(bool), "Option is one byte only");// can also map from void!
std::move(result)
.map([&]() -> std::string & { return world; })
.map([](auto ref) { std::cout << "got ref: " << *ref << "\n"; });return 0;
}
```