From 06f409edcbf653aa008ac0383609f13624bce9f7 Mon Sep 17 00:00:00 2001 From: Boris Kolpackov Date: Thu, 19 Jan 2017 13:58:23 +0200 Subject: Improve optional (has_value(), operator<>, std::hash<> specialization) --- butl/optional | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) (limited to 'butl/optional') diff --git a/butl/optional b/butl/optional index 0877f52..f6cc15e 100644 --- a/butl/optional +++ b/butl/optional @@ -5,7 +5,8 @@ #ifndef BUTL_OPTIONAL #define BUTL_OPTIONAL -#include // move() +#include // move() +#include // hash namespace butl { @@ -38,6 +39,7 @@ namespace butl T& operator* () {return value_;} const T& operator* () const {return value_;} + bool has_value () const {return !null_;} explicit operator bool () const {return !null_;} private: @@ -58,6 +60,37 @@ namespace butl { return !(x == y); } + + template + inline auto + operator< (const optional& x, const optional& y) -> decltype (*x < *y) + { + bool px (x), py (y); + return px < py || (px && py && *x < *y); + } + + template + inline auto + operator> (const optional& x, const optional& y) -> decltype (*x > *y) + { + return y < x; + } +} + +namespace std +{ + template + struct hash>: hash + { + using argument_type = butl::optional; + + size_t + operator() (const butl::optional& o) const + noexcept (noexcept (hash {} (*o))) + { + return o ? hash::operator() (*o) : static_cast (-3333); + } + }; } #endif // BUTL_OPTIONAL -- cgit v1.1