diff options
author | 2024-11-20 18:06:07 -0800 | |
---|---|---|
committer | 2024-11-20 18:33:39 -0800 | |
commit | 83c6f9eed4bd2a10a7d73a3a0ab92766dfd8867b (patch) | |
tree | 67b5c6c720c7d95212b96a047a6a8423edfa1408 /include/ftl | |
parent | 1a824fd33a5308b68d69cf5ea20184b5c690d8e9 (diff) |
Easier ftl::Flags construction
As demonstrated by the existing test, while it is possible to construct
a ftl::Flags<E> from multiple values, it requires an extra
`using namespace ftl::flag_operators` or alternatively a
`using ftl::flag_operators::operator|` to implicitly construct a
`ftl::Flags<E>` type.
But there is an easier way -- allow implicit construction from a
`std::initializer_list<E>`.
This means as an alternative to:
using namespace ftl::flag_operators;
ftl::Flags<E> x = E::A | E::B;
... one can instead write:
ftl::Flags<E> x = {E::A, E::B};
... and achieve the same initial value.
This change adds the new constructor overload.
Assignment from an initializer list automatically works, without having
to define a explicit `operator=(std::initializer_list<E>)`. Instead the
copy constuctor is used.
As a useful side effect, you can now also clear the flags by assigning
an empty initializer list:
ftl::Flags<E> x;
x = {}; // Clears x to zero
Bug: 185536303
Flag: EXEMPT New library code
Test: atest ftl_test
Change-Id: I1de7857c93ebef4fc5e6157aac9cf162b49943e1
Diffstat (limited to 'include/ftl')
-rw-r--r-- | include/ftl/flags.h | 10 |
1 files changed, 10 insertions, 0 deletions
diff --git a/include/ftl/flags.h b/include/ftl/flags.h index dbe3148fc5..a2a22ebebe 100644 --- a/include/ftl/flags.h +++ b/include/ftl/flags.h @@ -22,6 +22,7 @@ #include <bitset> #include <cstdint> #include <iterator> +#include <initializer_list> #include <string> #include <type_traits> @@ -40,6 +41,7 @@ class Flags { public: constexpr Flags(F f) : mFlags(static_cast<U>(f)) {} + constexpr Flags(std::initializer_list<F> fs) : mFlags(combine(fs)) {} constexpr Flags() : mFlags(0) {} constexpr Flags(const Flags<F>& f) : mFlags(f.mFlags) {} @@ -197,6 +199,14 @@ public: private: U mFlags; + static constexpr U combine(std::initializer_list<F> fs) { + U result = 0; + for (const F f : fs) { + result |= static_cast<U>(f); + } + return result; + } + static void appendFlag(std::string& str, const std::string_view& flag, bool& first) { if (first) { first = false; |