From 2f7fc20abf11a28011c828449142fb0df1ab858c Mon Sep 17 00:00:00 2001 From: Dan Goodliffe Date: Tue, 18 Oct 2016 22:07:57 +0100 Subject: Add operator/ for resolving optional things to a final thing --- libadhocutil/optionals.h | 30 +++++++++++++++++++++ libadhocutil/unittests/Jamfile.jam | 8 ++++++ libadhocutil/unittests/testOptionals.cpp | 46 ++++++++++++++++++++++++++++++++ 3 files changed, 84 insertions(+) create mode 100644 libadhocutil/optionals.h create mode 100644 libadhocutil/unittests/testOptionals.cpp diff --git a/libadhocutil/optionals.h b/libadhocutil/optionals.h new file mode 100644 index 0000000..f4d6b1a --- /dev/null +++ b/libadhocutil/optionals.h @@ -0,0 +1,30 @@ +#ifndef ADHOCUTIL_OPTIONALS_H +#define ADHOCUTIL_OPTIONALS_H + +#include + +namespace AdHoc { + template + auto + operator/(const A & a, const B & b) -> typename std::enable_if< + std::is_constructible::value && + !std::is_pointer::value && + std::is_convertible::value, + decltype(a ? *a : b)>::type + { + return (a ? *a : b); + } + + template + auto + operator/(const A & a, const B & b) -> typename std::enable_if< + std::is_constructible::value && + std::is_pointer::value, + decltype(a ? &*a : b)>::type + { + return (a ? &*a : b); + } +} + +#endif + diff --git a/libadhocutil/unittests/Jamfile.jam b/libadhocutil/unittests/Jamfile.jam index bf86e9c..5072f39 100644 --- a/libadhocutil/unittests/Jamfile.jam +++ b/libadhocutil/unittests/Jamfile.jam @@ -261,3 +261,11 @@ run boost_filesystem ; +run + testOptionals.cpp + : : : + BOOST_TEST_DYN_LINK + ..//adhocutil + boost_utf + ; + diff --git a/libadhocutil/unittests/testOptionals.cpp b/libadhocutil/unittests/testOptionals.cpp new file mode 100644 index 0000000..7e5b4b1 --- /dev/null +++ b/libadhocutil/unittests/testOptionals.cpp @@ -0,0 +1,46 @@ +#define BOOST_TEST_MODULE Buffer +#include + +#include +#include +#include +#include + +using namespace AdHoc; + +BOOST_AUTO_TEST_CASE ( general ) +{ + boost::optional x; + boost::optional y = 2.3; + IceUtil::Optional ix; + IceUtil::Optional iy = 4; + std::string * p = nullptr; + std::string * q = new std::string("str"); + boost::optional r; + IceUtil::Optional s; + + bool b(p); + BOOST_REQUIRE_EQUAL(false, b); + auto a1 = x / y; + BOOST_REQUIRE(a1); + BOOST_REQUIRE_EQUAL(2.3, *a1); + auto a2 = x / 10; + BOOST_REQUIRE_EQUAL(10, a2); + auto a3 = ix / 11; + BOOST_REQUIRE_EQUAL(11, a3); + auto a4 = iy / 11; + BOOST_REQUIRE_EQUAL(4, a4); + + auto s1 = p / s / r; + BOOST_REQUIRE(!s1); + auto s2 = q / s / r; + BOOST_REQUIRE(s2); + BOOST_REQUIRE_EQUAL("str", *s2); + + auto p1 = r / q; + BOOST_REQUIRE(p1); + BOOST_REQUIRE_EQUAL("str", *p1); + + delete q; +} + -- cgit v1.2.3