better-enums/example/3-switch.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

39 lines
814 B
C++

// Switch case exhaustiveness checking.
#include <iostream>
#include <enum.h>
ENUM(Channel, int, Red, Green, Blue);
void respond_to_channel(Channel channel)
{
// Try adding an extra case or removing one. Your compiler should issue a
// warning.
switch (channel) {
case +Channel::Red:
std::cout << "red channel" << std::endl;
break;
case +Channel::Green:
std::cout << "green channel" << std::endl;
break;
case +Channel::Blue:
std::cout << "blue channel" << std::endl;
break;
// A redundant case.
// case 3:
// break;
}
}
int main()
{
respond_to_channel(Channel::Red);
respond_to_channel(Channel::Blue);
respond_to_channel(Channel::Green);
return 0;
}