enum-flags icon indicating copy to clipboard operation
enum-flags copied to clipboard

ALLOW_FLAGS_FOR_ENUM in enum scope, allow inside classes

Open martinus opened this issue 5 years ago • 2 comments

Currently the ALLOW_FLAGS_FOR_ENUM has to be in global scope to work, which can be a bit cumbersome (see #26). Instead, I propose two different macros:

#define ALLOW_FLAGS_FOR_ENUM(Name) inline void enableEnumFlags(Name) {}
#define ALLOW_FLAGS_FOR_ENUM_IN_CLASS(Name) friend inline void enableEnumFlags(Name) {}

Which works nicely thanks to ADL with this is_flags implementation:

template <typename T, typename = void>
struct is_flags : std::false_type {};
template <typename T>
struct is_flags<T, decltype(enableEnumFlags(T{}))> : std::true_type {};

It is then possible (mandatory) to use ALLOW_FLAGS_FOR_ENUM(Whatever) directly after an enum is defined, whatever scope it may be, and ALLOW_FLAGS_FOR_ENUM_IN_CLASS(Whatever) if the enum is inside a class or struct.

Note that the enableEnumFlags name should be rather unique so it is not used by anyone else, so maybe it is a good idea to obfuscate it a bit more with e.g. a random number, e.g. enableFlagsfbc4db870f32e

martinus avatar Apr 12 '20 11:04 martinus

That would be nice.

~Just curious, could you explain why the friend is needed?~

Oh I get it now... It defines a friended non-member function.

NikolausDemmel avatar Apr 12 '20 12:04 NikolausDemmel

exactly. Also, if you just use static inline void enableEnumFlags(Name) {} instead of friend, then it's not possible to make the enum type private.

martinus avatar Apr 12 '20 13:04 martinus