better-enums/example/7-bitset.cc
Anton Bachin 1b3d1cc784 Forbade nearly all implicit conversions to integral types.
Each Better Enum now has an internal enum class type to which it is convertible,
instead of being convertible to the regular enum that defines its constants.
switch statements are compiled at the enum class type. This comes at the price
of the user having to type +Enum::Constant instead of Enum::Constant in cases,
in order to trigger an explicit promotion of the pre-C++11 enum to Better Enum,
so it can then be implicitly converted to the enum class.

The remaining "hole" is that direct references to constants (Enum::Constant) are
still implicitly convertible to integral types, because they have naked
pre-C++11 enum type.
2015-05-18 19:56:17 -05:00

45 lines
1.1 KiB
C++

// Usage with std::bitset.
#include <bitset>
#include <iostream>
#include <enum.h>
// Computes the maximum value of an enum at compile time.
template <typename Enum>
constexpr Enum maximum(Enum accumulator = Enum::_values[0], size_t index = 1)
{
return
index >= Enum::_size ? accumulator :
+Enum::_values[index] > accumulator ?
maximum(+Enum::_values[index], index + 1) :
maximum(accumulator, index + 1);
}
ENUM(Channel, int, Red, Green, Blue);
int main()
{
using ChannelSet = std::bitset<maximum<Channel>().to_integral() + 1>;
ChannelSet red_only;
red_only.set(Channel::Red);
ChannelSet blue_only;
blue_only.set(Channel::Blue);
ChannelSet red_and_blue = red_only | blue_only;
for (Channel channel : Channel::_values) {
std::cout
<< channel.to_string()
<< " bit is set to "
<< red_and_blue[channel.to_integral()]
<< std::endl;
}
if (red_and_blue[Channel::Green])
std::cout << "bit set contains Green" << std::endl;
return 0;
}