lundi 14 février 2022

C++ statically assert that only certain enum values are present

I have a enum with that looks like this:

enum class States{
     STATE_A,
     STATE_B,
     STATE_C,
     STATE_D,
     STATE_E
}

And I have a guard somewhere where I am checking:

if( state == STATE_A || state = STATE_C || state == STATE_D || state == STATE_E)

so excluding STATE_B. I have done this deliberately so that the inclusion of another state does not change existing behaviour. The question here would be if I can have both, meaning the convenience of writing state != STATE_B and compile time robustness against changes to the States enum.

I would think that this can be done with a static_assert somehow but how would I go about that? The States do not have any assigned value nor particular ordering.

Aucun commentaire:

Enregistrer un commentaire