4 ms·
Is there any clean way to use an Option/Maybe monad in C (or C++)? It should be a simple way to solve problems where error codes are valid inputs of other funct
by JD557 12y ago
Is there any clean way to use an Option/Maybe monad in C (or C++)? It should be a simple way to solve problems where error codes are valid inputs of other functions.
The simplest way I can think of is:
struct maybe {
bool isEmpty;
void* value;
}
Although I wonder if using C++ templates, classes and operator overloading is possible to make a more practical implementation (using void* does seem like a bad idea).
- sbmassey 12y agoIn C++ std::optional<T> does the trick, as of version 11, and boost::optional<T> previously. In C ... hrm you could probably wrangle some macros around that struct if you were desperate.
- pbsd 12y agoNitpick: std::optional<T> does not exist in C++11, nor in the recently-approved C++14. It is, nevertheless, in the process of getting into the standard, and is already present in GCC 4.9's libstdc++ as std::experimental::optional.
- whyever 12y agoUnfortunately `std::optional` did not get accepted for C++14, because it's implementation uses some hacks that are undefined behavior by the standard (but work on the major compilers).
- MichaelGG 12y agoThe problem is solved, but consider the overhead of all this. You now need an extra byte somewhere (register, stack space, whatever) to track the tag. I would imagine that this, and lack of handy syntax, is why lower-level APIs don't offer better return values.