How to use std :: optional in C ++

In C ++ 17 std::optional, I was pleased with this solution until I looked at ref. I know Optional/ Maybefrom Scala, Haskell, and Java 8, where optional is a monad and follows monadic laws. This does not apply to the C ++ implementation 17. How should I use std::optional, without features such as mapand flatMap/ bind, what is the benefit of using std::optionalvs, for example, return -1or nullptrof the function if it can not calculate the result? And more importantly for me, why wasn’t it std::optionalintended for the monad, is there a reason?

+4
source share
2 answers

std:: optional, , map flatMap/bind

Maybe Haskell fmap, , . , .

std:: optional vs, , -1 nullptr , ?

, ? 0, -1, MAX_INT, nullptr - ? unsigned int, int int, -1, MAX_INT, ? std::optional .

, std:: optional, , ?

++ ? , , .

+3

bind return std::optional, .

, bind

template<typename T1, typename T2>
std::optional<T2> bind(std::optional<T1> a, std::function< std::optional<T2>(T1)> f) {
   if(a.has_value()) return f(a.value());
   return std::optional<T2>{};
 }

, , .

, , - , , .

+2

Source: https://habr.com/ru/post/1657522/


All Articles