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
diff --git a/include/ftl/flags.h b/include/ftl/flags.h
index dbe3148..a2a22eb 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 @@
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 @@
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;