Hi everyone, long time no see!
I would like to propose a new library for the Beman Project: beman.monadics.
C++23 introduced monadic operations for std::expected, and C++26 extends them to std::optional. But raw pointers, smart pointers, and many third-party types currently have no unified monadic interface. beman.monadics aims to provide a free-function, extensible monadic interface for any “box-like” type.
P.S. I first proposed this idea during C++Now 2025 Library in a Week, but unfortunately didn’t have time to follow up back then.
Design
Operations are free functions and support pipeline syntax:
namespace bms = beman::monadics;
std::optional{10}
| bms::and_then([](auto&& v){ return std::optional{v*2}; })
| bms::transform([](auto v){ return static_cast<int>(v); })
| bms::or_else([](){ return std::optional{0}; });
Core operations:
-
and_then -
transform -
or_else -
transform_error
All operations preserve value category and const correctness.
Customization
Types opt in via box_traits (similar to std::formatter):
template <typename Box>
struct beman::monadics::box_traits;
The full interface looks like this:
template <typename Box>
struct beman::monadics::box_traits<Box> {
using value_type = ...;
using error_type = ...;
template <typename T>
using rebind = ...;
template <typename E>
using rebind_error = ...;
static constexpr bool has_value(const Box&) noexcept { ... }
static constexpr value_type value(auto&&box) noexcept { ... }
static constexpr decltype(auto) error(auto&&box) noexcept { ... }
static constexpr decltype(auto) make(auto&& v) noexcept { ... }
static constexpr decltype(auto) make_error(auto&& e) noexcept { ... }
};
Some members are optional. For example, std::optional only requires the error() member; the rest (has_value, value, value_type, rebind, etc.) can be deduced automatically via template metaprogramming. Similarly, make and make_error can be generated if the type is constructible from a value and/or error.
Examples:
-
expected - box_traits, usage
-
optional - box_traits, usage
-
shared_ptr - box_traits, usage
-
raw pointer - box_traits, usage
-
enum CURLCode - box_traits, usage
Status & Background
-
Experimental prototype with tests and CI passing
-
Willing to maintain and evolve under Beman
Repository: https://github.com/msvetkin/monadics
Questions
-
Is this still something the project is interested in?
-
If yes, what is the process?
-
Design review
-
Submission steps
-
-
Should the initial scope be even smaller?
-
Who can help with writing a paper?