Skip to content

Commit fb5eba9

Browse files
authored
Create a flag_set out of an integral value (#161)
Fixes #160.
1 parent ae6d075 commit fb5eba9

2 files changed

Lines changed: 36 additions & 0 deletions

File tree

include/type_safe/flag_set.hpp

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,11 @@ namespace detail
115115
return flag_set_impl(int_type(0));
116116
}
117117

118+
static constexpr flag_set_impl from_int(int_type intVal)
119+
{
120+
return flag_set_impl(int_type(intVal));
121+
}
122+
118123
explicit constexpr flag_set_impl(const Enum& e) : bits_(mask(e)) {}
119124
template <typename Tag2>
120125
explicit constexpr flag_set_impl(const flag_set_impl<Enum, Tag2>& other)
@@ -416,6 +421,17 @@ class flag_set
416421
static_assert(flag_set_traits<Enum>::value, "invalid enum for flag_set");
417422

418423
public:
424+
using int_type = typename detail::flag_set_impl<Enum>::int_type;
425+
426+
/// \returns a flag_set based on the given integer value.
427+
/// \requires `T` must be of the same type as `int_type`.
428+
template <typename T>
429+
static constexpr flag_set from_int(T intVal)
430+
{
431+
static_assert(std::is_same<T, int_type>::value, "invalid integer type, lossy conversion");
432+
return flag_set(intVal);
433+
}
434+
419435
//=== constructors/assignment ===//
420436
/// \effects Creates a set where all flags are set to `0`.
421437
/// \group ctor_null
@@ -609,6 +625,9 @@ class flag_set
609625
}
610626

611627
private:
628+
explicit constexpr flag_set(int_type rawvalue) noexcept : flags_(detail::flag_set_impl<Enum>::from_int(rawvalue))
629+
{}
630+
612631
detail::flag_set_impl<Enum> flags_;
613632

614633
friend detail::get_flag_set_impl;

test/flag_set.cpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,23 @@ TEST_CASE("flag_set")
153153
b = test_flags::c;
154154
check_set(b, false, false, true);
155155
}
156+
SECTION("from_int")
157+
{
158+
set a = set::from_int<std::uint8_t>(0b000);
159+
check_set(a, false, false, false);
160+
161+
a = set::from_int<std::uint8_t>(0b001);
162+
check_set(a, true, false, false);
163+
164+
a = set::from_int<std::uint8_t>(0b010);
165+
check_set(a, false, true, false);
166+
167+
a = set::from_int<std::uint8_t>(0b100);
168+
check_set(a, false, false, true);
169+
170+
a = set::from_int<std::uint8_t>(0b111);
171+
check_set(a, true, true, true);
172+
}
156173
SECTION("set")
157174
{
158175
s.set(test_flags::a);

0 commit comments

Comments
 (0)