Ensuring coverage of all enumeration values ​​on the map

Say I have the following:

#include <map>

enum class Thing {Zero, One, Two};

class Metadata {};

std::map<Thing, Metadata> extra_info;

void foo() {
    extra_info[Thing::Zero] = Metadata();
    extra_info[Thing::One] = Metadata();
    extra_info[Thing::Two] = Metadata();
}

I would like to make sure that all tags Thingare counted in extra_info, in case of adding a new tag, for example Thing::Three.

I believed that it always has a tag at the end, LastTagand iterating from 0to LastTag - 2and verifying that these keys exist on the map, but it looks like kludgy. It would be best to do this at compile time, but I see that this is not possible at all.

In C #, it is a simple thing to use reflection to get all the enumeration values ​​and then iterate over them. I think this suggests that I cannot find the answer for this with the C ++ tag, but I can find the answers in Java and C # ... Which makes me think that this is impossible.

+4
1

Sentinel , .

, ( ):

enum class Thing { Zero, One, Two, Three, EndSentinel };

class Metadata {};

std::map<Thing, Metadata> extra_info;
typedef std::map<Thing, Metadata>::size_type map_type;

void foo() {
    // Can't forget these values
    extra_info[Thing::Zero] = Metadata();
    extra_info[Thing::One] = Metadata();
    extra_info[Thing::Two] = Metadata();
    extra_info[Thing::Three] = Metadata();
}

int main() {
    foo();

    assert(extra_info.size() == (map_type)Thing::EndSentinel);
}

+1

All Articles