stlab-enum-ops 1.0.0
Type-safe operators for enums
Loading...
Searching...
No Matches
Typesafe Integers and Bit Fields (enums)

View on GitHub

Description

enum_ops provides optional typesafe bitset and arithmetic operations for enumeration types. Without these typesafe operations, the compiler will promote the operand(s) to the appropriate integral type, and the result will be an integral type. When the typesafe operations have been defined for an enumeration type, E, the result will be of type E exactly when the operand(s) are of type E.

auto stlab_enable_bitmask_enum(E) -> std::true_type;

Enables the bitset operations, ~, |, &, ^, |=, &=, and ^=, for enumeration type E.

auto stlab_enable_arithmetic_enum(E) -> std::true_type;

Enables the typesafe arithmetic operations +, -, *, /, %, +=, *=, -=, /=, and %=, for enumeration type E.

Definition

Defined in stlab/enum_ops.hpp

Example

The following is an example of code that will compile:

#include <iostream>
enum foo { foo_4 = 1 << 2, foo_8 = 1 << 3 };
enum class views : int { none = 0, text = 1 << 0, icon = 1 << 1, preview = 1 << 2 };
auto stlab_enable_bitmask_enum(foo) -> std::true_type;
auto stlab_enable_bitmask_enum(views) -> std::true_type;
int main() {
// Bitset operations on plain enums
foo a{foo_4};
foo b{foo_8};
foo c{a | b};
std::cout << a << " " << b << " " << c << "\n";
// Bitset operations on enum class
views x = views::text | views::icon;
bool has_text = (x & views::text) == views::text;
bool has_preview = (x & views::preview) == views::preview;
std::cout << has_text << " " << has_preview << "\n";
}
Typesafe operators for enum types enabled via opt-in customization points.
auto stlab_enable_bitmask_enum(...) -> std::false_type

The following is contains an example of code that will not compile since the typesafe operators have not been defined.

enum foo { foo_4 = 1 << 2, foo_8 = 1 << 3 };
enum bar { bar_4 = 1 << 2, bar_8 = 1 << 3 };
enum baz { baz_4 = 1 << 2, baz_8 = 1 << 3 };
auto stlab_enable_arithmetic_enum(baz) -> std::true_type;
int main() {
foo a{foo_4};
bar b{bar_8};
foo c{a + b}; // Error! a and b are different enum types, so result is integral
baz d{baz_4};
baz e{baz_8};
baz f{d + e}; // Ok, arithmetic ops enabled for baz, so d + e has type baz
}
auto stlab_enable_arithmetic_enum(...) -> std::false_type