Re: enum count

Discussion in 'C++' started by Klaus Eichner, Jul 26, 2003.

  1. "Clive" <> wrote in message
    news:3f21e5cc$0$23611$...
    > If you have an enum, is there any way during execution to find the number

    of
    > values in the enum?
    > Say I have,
    >
    > enum great { five, ten, fifteen };
    >
    > How could I get the number 3 from that?


    You could get the number 3 from 'great' with your own, user-defined
    'Enum_Info' template:

    cout << "The number of values in enum great is "
    << Enum_Info<great>::number_of_elements
    << endl;

    The 'Enum_Info' template is defined as follows.
    Suppose you have the following enums:

    enum great { five, ten, fifteen };
    enum greater { none, one, fourtytwo, fourtythree, fourtyfour };
    enum even_greater { minusone, minustwo, minusthree, minusfour, minusfive,
    minussix, minusseven };

    You could build a template class 'Enum_Info' which uses specialisation to
    register the number of elements in each enum

    template <class T> class Enum_Info { };
    template <> class Enum_Info<great> { static const int number_of_elements =
    3; };
    template <> class Enum_Info<greater> { static const int number_of_elements =
    5; };
    template <> class Enum_Info<even_greater> { static const int
    number_of_elements = 7; };
    Klaus Eichner, Jul 26, 2003
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. -

    enum within an enum

    -, Jun 12, 2005, in forum: Java
    Replies:
    6
    Views:
    533
  2. Jerminia
    Replies:
    3
    Views:
    622
    Roedy Green
    Oct 7, 2005
  3. Ernst Murnleitner

    How to enum an enum?

    Ernst Murnleitner, Nov 12, 2003, in forum: C++
    Replies:
    5
    Views:
    457
    Rolf Magnus
    Nov 13, 2003
  4. mrhicks
    Replies:
    2
    Views:
    415
    Dave Thompson
    Jun 10, 2004
  5. Randy
    Replies:
    1
    Views:
    516
    David Harmon
    Jan 7, 2006
Loading...

Share This Page