-
-
Save slurpyb/1692a7c1f8dbd4c92749206a541aa6fc to your computer and use it in GitHub Desktop.
scoped_flags for c++11 scoped enumerations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
template <class T> | |
class scoped_flags | |
{ | |
public: | |
using value_type = std::underlying_type_t<T>; | |
scoped_flags(std::initializer_list<T> flag_list) | |
: value_(combine_(flag_list)) | |
{ | |
} | |
scoped_flags() | |
: value_(0) | |
{ | |
} | |
bool test(T flag) const | |
{ | |
return value_ & static_cast<value_type>(flag); | |
} | |
bool test(std::initializer_list<T> flag_list) const | |
{ | |
auto other = combine_(flag_list); | |
return (value_ & other) == other; | |
} | |
scoped_flags<T> with(T flag) const | |
{ | |
return { value_ | static_cast<value_type>(flag) }; | |
} | |
scoped_flags<T> changed(T flag, bool enabled) const | |
{ | |
return enabled ? with(flag) : without(flag); | |
} | |
scoped_flags<T> with(std::initializer_list<T> flag_list) const | |
{ | |
return { value_ | combine_(flag_list) }; | |
} | |
scoped_flags<T> without(T flag) const | |
{ | |
return { value_ & ~(static_cast<value_type>(flag)) }; | |
} | |
value_type to_underlying_type() const | |
{ | |
return value_; | |
} | |
static scoped_flags<T> from_underlying_type(value_type value) | |
{ | |
return {value}; | |
} | |
private: | |
static value_type combine_(std::initializer_list<T> flag_list) | |
{ | |
auto value = 0; | |
for (auto each : flag_list) | |
value |= static_cast<value_type>(each); | |
return value; | |
} | |
scoped_flags(value_type value) | |
: value_(value) | |
{ | |
} | |
value_type value_; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment