如何获取枚举元素的数量? [英] How to get the number of elements of an enum?

查看:104
本文介绍了如何获取枚举元素的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,

我创建了一个结构,例如,

Hello,
I have created one struture like,

typedef enum
{
   NAME = 0,
   ADDRESS,
   BIRTHDATE,
}INFORMATION



我想获得此结构中的元素数量。有没有函数?


And I want to get Number of elements in this structure. Is there any function?

推荐答案

考虑到你给出的结构是:



Considering the structure that is given by you is:

typedef enum
{
MIN = 0,
NAME  = MIN,
ADDRESS,
BIRTHDATE,
MAX = BIRTHDATE
};
int NumOfElement = MAX-MIN+1;





或直接BIRTHDATE + 1(如果Enum从0开始)。



Or directly BIRTHDATE + 1 (if Enum start with 0).


以你问的方式...

没有可以提供这样的功能(要执行的代码)结果,因为标准C ++有无反射

标准RTTI专为支持dynamic_cast而定制,并且在枚举上没有任何作用。



如果我们考虑一些语言扩展(比如C ++ / CLI,这是一个不被C ++标准的所有者ANSI接受的ECMA标准......),可能会增加反射,从而增加反射能力在运行时查询源的状态。



当然可以有一些技巧,比如

In the way you asked ... NO.
There is no function (code to be executed) that can give such a result, since standard C++ has no reflection.
The standard RTTI is tailored to support dynamic_cast and have no role on enums.

Things may be different if we consider some language extensions (like C++/CLI, that is an ECMA standard not accepted by ANSI that is the owner of the C++ standard ...) that can add reflection and hence the capability to query at runtime the state of the source.

Of course there can be tricks like
enum E
{
    a,b,c, count;
};



导致a = 0,b = 1,c = 2,count = 3。但这与你提出的问题有所不同(可能是不合适的,出于特定目的)。


That leads to a=0, b=1, c=2, count=3. But that's a different thing respect to what you asked (may be not adequate, for certain purpose).


我同意SA,但是在进行通用编程和考虑未来的可扩展性时,我们总是在枚举中添加eENUMLast,这样如果我们添加/删除任何枚举值,eENUMLast总是保持最后。
I am agree with SA, however while doing generic programming and thinking about future extensibility, we always add eENUMLast in enum, so that if we add/delete any enumerated value, eENUMLast always remain last.


这篇关于如何获取枚举元素的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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