Skip to content

Instantly share code, notes, and snippets.

@cbsmith
Created September 5, 2018 02:34
Show Gist options
  • Save cbsmith/f6535847f74d5553f19b41a849d19ec0 to your computer and use it in GitHub Desktop.
Save cbsmith/f6535847f74d5553f19b41a849d19ec0 to your computer and use it in GitHub Desktop.
A handy implementation of fmap that is apparently missing in the standard.
#ifndef FMAP_HPP__INCLUDE
#define FMAP_HPP__INCLUDE
#include <optional>
namespace nonstd {
template <typename F, typename T>
auto fmap(F f, std::optional<T> x) -> std::optional<decltype(f(std::forward<T>(*x)))> {
return (x.has_value()) ?
std::make_optional(f(std::forward<T>(*x))) :
std::nullopt;
}
//be nice to senile programmers
template <typename T, typename F>
auto fmap(std::optional<T> x, F f) -> decltype(fmap(f, x)) {
return fmap(f, x);
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment