Using enum in loops and value consistency

前端 未结 2 1086
傲寒
傲寒 2020-12-10 20:16

I\'m a big fan of C++\'s strong-typing features and what I like the most is to use enumerations while dealing with limited sets of data.

But enumerations lack some u

2条回答
  •  爱一瞬间的悲伤
    2020-12-10 20:51

    You can use a switch:

    class Invalid {};
    Prime& operator ++(Prime& p)
    {
        switch(p)
        {
            case n00: return n01;
            case n01: return n02;
            case n02: return n03;
            case n03: return n04;
            case n04: return n05;
            case n05: return n06;
            case n06: return n07;
            case n07: return n08;
            case n08: return n09;
            case n09: return n10;
            case n10: return n11;
            case n11: return n12;
            case n12: return n13;
            case n13: return n14;
            case n14: return n15;
            // Here: 2 choices: loop or throw (which is the only way to signal an error here)
            case n15: default: throw Invalid();
        }
    }
    

    But note that this is not the right use of enums. I personally find this error-prone. If you want to enumerate integers, you can use an array of ints to do this, or for the case of prime numbers, a function (in mathematical sense: int nextPrime(int)).

提交回复
热议问题