Jump to: navigation, search

Dead C++ Society/C++11 bitflags

Dead C++ Society/C++11 bitflags


There are cases where you want to use bit flags. This was usually implemented using #define or classis enums and bitwise operators. This pages is devoted in seek of a new approach using new C++x11 features.

// This is a draft of an idea of a c++x11 wrapper to work with bitflags
template<class E>
	class bitflags {
	public:

		typedef E opt;

		typedef unsigned base_type;

		bitflags() = default;

		bitflags (E val):
			m_val(val) {
		}

		bitflags(std::initializer_list<E> flags) :
			m_val(E(0)){
			for(auto f : flags) {
				m_val = E((base_type)m_val | (base_type)f);
			}
		}

		base_type get_base() const{
			return (base_type)m_val;
		}

		bitflags operator~() const {
			base_type inter = ~get_base();
			return bitflags((E)inter);
		}

		bitflags operator&(const bitflags & r) const {
			return bitflags(E(get_base() & r.get_base()));
		}

		bitflags operator|(const bitflags & r) const {
			return bitflags(E(get_base() & r.get_base()));
		}

		bool has_flag(E val) {
			return (base_type(m_val) & base_type(val)) != 0;
		}

		operator E () {
			return m_val;
		}

		static bitflags _and(E lv, E rv) {
			return bitflags(lv) & bitflags(rv);
		}

	protected:
		E m_val;
	};