是否可以确定一个c ++枚举类的元素数量? [英] Is it possible to determine the number of elements of a c++ enum class?

查看:807
本文介绍了是否可以确定一个c ++枚举类的元素数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以确定c ++ 枚举类的基数

enum class Example { A, B, C, D, E };



我尝试使用 sizeof 它返回枚举元素的大小。

I tried to use sizeof, however, it returns the size of an enum element.

sizeof(Example); // Returns 4 (on my architecture)

有一个标准的方法来获得基数

Is there a standard way to get the cardinality (5 in my example) ?

推荐答案

不直接,但你可以使用以下技巧:

Not directly, but you could use the following trick:

enum class Example { A, B, C, D, E, Count };

然后基数可用(int)Example :: Count

Then the cardinality is available as (int)Example::Count.

当然,如果你让枚举的值自动从0开始,那么这只能很好地工作。如果不是这样,可以手动为Count指定正确的基数,这与必须保持单独的常数无关:

Of course, this only works nicely if you let values of the enum be automatically assigned, starting from 0. If that's not the case, you can manually assign the correct cardinality to Count, which is really no different from having to maintain a separate constant anyway:

enum class Example { A = 1, B = 2, C = 4, D = 8, E = 16, Count = 5 };

一个缺点是编译器会允许你使用 Example ::计数作为枚举值的参数 - 所以一定要小心,如果你使用这个! (我个人认为这在实践中不是一个问题。)

The one disadvantage is that the compiler will allow you to use Example::Count as an argument for an enum value -- so be careful if you use this! (I personally find this not to be a problem in practice, though.)

这篇关于是否可以确定一个c ++枚举类的元素数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆