home *** CD-ROM | disk | FTP | other *** search
- From: peterj@hparc0.aus.hp.com (Peter Westley)
- Date: Thu, 21 Jan 1993 05:40:36 GMT
- Subject: smart enums
- Message-ID: <1993Jan21.054036.27343@hparc0.aus.hp.com>
- Organization: HP Australasian Response Centre (Melbourne)
- Path: sparky!uunet!usc!sdd.hp.com!hpscit.sc.hp.com!hplextra!hpcc05!hparc0.aus.hp.com!peterj
- Newsgroups: comp.lang.c++
- X-Newsreader: Tin 1.1 PL4
- Lines: 69
-
- I am trying to create a class which implements a "smart enum". This enum
- type will be able recognise itself as both an int (or other integral type)
- or as char* and also have stndard conversions to both int and char* for
- things sunch as stream insertion.
-
- The way I am trying to implement them is with templates. Say I wanted
- an enum class type which could take the values "Apple", "Banana" and "Pear"
- each assigned (an arbitary) int. Basically to bahave much as an enum normally
- does.
-
- In order to do this I decleared a template like:
-
- template <char **l>
- class SmartEnum
- {
- public:
- SmartEnum();
- SmartEnum(char *);
- SmartEnum(int);
- //etc
- private:
- int val;
- char **names;
- }
-
- template <char **nm> SmartEnum<nm>::SmartEnum()
- {
- //what ever
- }
-
- The idea being that I could declare a class based on this template which
- I could have multiple instances of:
-
- char *somenames[] = {"Apple","Banana","Pear"};
- char *morenames[] = {"Peter","John","Andrew"};
-
- typedef SmartEnum<somenames> FruitEnum;
- typedef SmartEnum<morenames> BoysEnum;
- FruitEnum aFruit();
- FruitEnum anotherFruit();
- BoysEnum aBoy();
- BoysEnum anotherBoy();
-
- Then I could do things like:
- aFruit = "Banana";
- anotherFruit = 1;
- aBoy = "Andrew";
- anotherBoy = 1;
-
- And (while I haven't declared these in my example because I'm too lazy) you
- could use them like:
- cout << (int)aBoy; //gives "3"
- cout << (char *)anotherBoy; //gives "Peter"
- etc etc
-
- Am I going about this the right way? Have I totally missed something?
- Is there A Better Way? Should I be using templates?
-
- Free comments welcome - even flames!!
-
- Peter Westley .-_!\ Hewlett Packard
- Phone: +61 3 (T)272 2440 / \ Australian Support Centre
- Fax: +61 3 890 0326 \_.-.b/<--------31-41 Joseph St.
- E-mail: peterj@hparc0.aus.hp.com v Blackburn, Victoria 3130
- //
- // The views, opinions, information or other data here is solely from the
- // mind of myself. It is not the official word from my employer. While I
- // endeavour to provide accurate information, no responsibility is taken
- // for errors or omissions.
-