Skip to content

Commit

Permalink
Provide support for explicit operator bool (foonathan#79)
Browse files Browse the repository at this point in the history
  • Loading branch information
kyku authored and foonathan committed May 26, 2018
1 parent 9ed89d6 commit 367f2dc
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
12 changes: 12 additions & 0 deletions include/type_safe/strong_typedef.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,18 @@ namespace type_safe
TYPE_SAFE_DETAIL_MAKE_STRONG_TYPEDEF_OP(division, /)
TYPE_SAFE_DETAIL_MAKE_STRONG_TYPEDEF_OP(modulo, %)

template <class StrongTypedef>
struct explicit_bool
{
/// \exclude
explicit constexpr operator bool() const
{
return static_cast<bool>(
detail::get_underlying<StrongTypedef>(
static_cast<const StrongTypedef&>(*this)));
}
};

template <class StrongTypedef>
struct increment
{
Expand Down
36 changes: 36 additions & 0 deletions test/strong_typedef.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -573,4 +573,40 @@ TEST_CASE("strong_typedef")
in >> a;
REQUIRE(static_cast<int>(a) == 1);
}
SECTION("explicit bool")
{
struct type : strong_typedef<type, int>,
strong_typedef_op::explicit_bool<type>
{
using strong_typedef::strong_typedef;
};

type a(0);
REQUIRE(!a);
type b(1);
REQUIRE(b);
}
SECTION("explicit bool nonconstexpr")
{
struct foo
{
bool flag;

explicit operator bool() const
{
return flag;
}
};

struct type : strong_typedef<type, foo>,
strong_typedef_op::explicit_bool<type>
{
using strong_typedef::strong_typedef;
};

type a(foo{false});
REQUIRE(!a);
type b(foo{true});
REQUIRE(b);
}
}

0 comments on commit 367f2dc

Please sign in to comment.