Skip to content

Instantly share code, notes, and snippets.

@tyanmahou
Last active October 12, 2017 02:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tyanmahou/5209db3041236fb1d216923ee4fba4a4 to your computer and use it in GitHub Desktop.
Save tyanmahou/5209db3041236fb1d216923ee4fba4a4 to your computer and use it in GitHub Desktop.
IntegerEnum
#pragma once
namespace ie
{
namespace detail
{
struct Value
{
constexpr Value() = default;
constexpr Value(const int& other) :
value(other)
{}
protected:
int value = 0;
};
}
}
#define INTEGER_ENUM(...)\
struct : ie::detail::Value{\
using _ENUM=enum { __VA_ARGS__ };\
using Value::Value;\
decltype(auto) operator +=(int value) { *this = this->value + value; return *this; }\
decltype(auto) operator -=(int value) { *this = this->value - value; return *this; }\
decltype(auto) operator *=(int value) { *this = this->value * value; return *this; }\
decltype(auto) operator /=(int value) { *this = this->value / value; return *this; }\
decltype(auto) operator %=(int value) { *this = this->value % value; return *this; }\
decltype(auto) operator ++() { *this = this->value + 1; return *this; }\
decltype(auto) operator --() { *this = this->value - 1; return *this; }\
decltype(auto) operator ++(int) { auto ret = *this; *this = this->value + 1; return ret; }\
decltype(auto) operator --(int) { auto ret = *this; *this = this->value - 1; return ret; }\
constexpr operator _ENUM()const{ return static_cast<_ENUM>(value); }\
}
/*
using Example = INTEGER_ENUM(
A,
B,
Default = A
);
*/
#include<iostream>
#include<string>
#include"IntegerEnum.hpp"
using Example = INTEGER_ENUM(
A,
B,
C=10,
Default = A
);
//enum class 同様名前の衝突なし
using Example2 = INTEGER_ENUM(
A,
B
);
int main()
{
Example test1 = Example::Default;
test1 += 2; //整数の演算可能
constexpr Example c{ 0 }; //constexpr対応
//enumのように扱える
int a[Example::C];
int b = Example::A;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment