Is there a good way to ensure that specific switch statement handles all enum values?

Viewed 230

I have an enum

enum class Colors {
    RED,
    GREEN,
    BLUE
}

and a switch statement:

switch (Colors) {
    case Colors::RED:
        //do something
        break;
    case Colors::GREEN:
        //do something
        break;
    case Colors::BLUE:
        //do something
        break;
}

Is there a good way to ensure that this switch statement always has the same amount of nodes as number of values in 'Colors' and throw an error at compile time if not? I need this to work only on this specific switch statement, not other switch statements.

EDIT: for MSVC this works:

#pragma warning(push)
#pragma warning (default: 4062)
#pragma warning (error: 4062)
function_to_which_the_warning_is_applied() {}
#pragma warning(pop)
1 Answers

Basically configure compiler options in desired way.

The simplest choice (which will cover other common mistakes) is to use -Wall -Werror for gcc or clang and /W4 /WX for msvc (/W4 do not cover respective warning so /we4062 is needed, /WX /Wall detects to much issues from standard header files).
https://godbolt.org/z/3sEvnP

You can also configure single warning: -Wswitch-enum /we4062.
https://godbolt.org/z/f1ox8E

Related