The question:
How can I get the compiler to warn me when I haven't included a branch for every possible value of a type? This is especially relevant when I am coding with a type that may gain values later (std::variant
or an enum
).
Example:
Here is the code I am playing with (in an attempt to make this work):
enum MyEnum {
ECHAD
,SHTAYIM
// ,SHALOSH
};
int main() {
MyEnum x = ECHAD;
switch (x) {
case ECHAD:
std::cout << "One" << std::endl;
break;
case SHTAYIM:
std::cout << "Two" << std::endl;
break;
default:
static_assert(false, "You haven't handled every possible value of MyEnum");
}
}
And here is a godbolt with the following code: https://godbolt.org/z/Kn76q8naq
In my mental model, this should compile. Because every possible value of MyEnum
has been accounted for. So the default
branch need not get compiled. That is, until SHALOSH
gets added to the enum. THEN the compiler should jump in and point this out to me.
More explanation
exhaustiveness checking serves as a kind of refactoring tool. Whenever you expand the possibilities in a type, the compiler will point you to the places where you forgot to handle the new cases you just created
For a fuller explanation please see this blog post: https://blog.janestreet.com/what-do-haskellers-have-against-exhaustiveness/ and the talk linked within it.