Skip to content

Commit 2c07b1e

Browse files
committed
Add Optional::map.
1 parent 83864e9 commit 2c07b1e

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

llvm/include/llvm/ADT/Optional.h

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,14 @@ template <typename T> class Optional {
267267
return hasValue() ? getValue() : std::forward<U>(value);
268268
}
269269

270+
/// Apply a function to the value if present; otherwise return None.
271+
template <class Function>
272+
auto map(const Function &F) const
273+
-> Optional<decltype(F(getValue()))> {
274+
if (*this) return F(getValue());
275+
return None;
276+
}
277+
270278
#if LLVM_HAS_RVALUE_REFERENCE_THIS
271279
T &&getValue() && { return std::move(Storage.getValue()); }
272280
T &&operator*() && { return std::move(Storage.getValue()); }
@@ -275,6 +283,14 @@ template <typename T> class Optional {
275283
T getValueOr(U &&value) && {
276284
return hasValue() ? std::move(getValue()) : std::forward<U>(value);
277285
}
286+
287+
/// Apply a function to the value if present; otherwise return None.
288+
template <class Function>
289+
auto map(const Function &F) &&
290+
-> Optional<decltype(F(std::move(*this).getValue()))> {
291+
if (*this) return F(std::move(*this).getValue());
292+
return None;
293+
}
278294
#endif
279295
};
280296

0 commit comments

Comments
 (0)