Movatterモバイル変換


[0]ホーム

URL:


Wayback Machine
4 captures
17 Nov 2010 - 14 Dec 2011
NovDECJan
Previous capture14Next capture
201020112012
success
fail
COLLECTED BY
Organization:Alexa Crawls
Starting in 1996,Alexa Internet has been donating their crawl data to the Internet Archive. Flowing in every day, these data are added to theWayback Machine after an embargo period.
Collection:Alexa Crawls
Starting in 1996,Alexa Internet has been donating their crawl data to the Internet Archive. Flowing in every day, these data are added to theWayback Machine after an embargo period.
TIMESTAMPS
loading
The Wayback Machine - https://web.archive.org/web/20111214095211/http://www.codeproject.com:80/KB/cpp/smart_cpp_enum.aspx
Click here to Skip to main content
8,333,628 members and growing!
EmailPassword Lost password?
Home
Search within:




Licence CPOL
First Posted 13 Nov 2010
Views 8,709
Downloads 103
Bookmarked 12 times

Typesafe C++ Enum with ToString() and FromString()

Bypasztorpisti | 13 Nov 2010
An enum with macro + template magic, providing type safety and type info
 
See Also
Print Article
add
Add to your CodeProject bookmarks
Discuss
Discuss this article
12
  4.25 (8 votes)

1
1 vote, 12.5%
2

3
3 votes, 37.5%
4
4 votes, 50.0%
5
4.25/5 - 8 votes
μ 4.25, σa 1.81 [?]
Sponsored Links

Introduction

C++enums lack some features that coders often need. For example, the value of the last member to be able to iterate through the possible values of anenum. This problem is usually solved by adding a "last" member to theenum:

enum MyEnum{  MyEnum_member1,  MyEnum_member2,  MyEnum_Last};

Another thing that causes headaches is the conversion between anenumvalue and itsstringrepresentation. Most people, especially beginners, end up with something like this to be able to perform the conversion:

staticconstchar* ENUM_STRINGS[MyEnum_Last] ={"MyEnum_member1","MyEnum_member2",};

The code attached to this article provides a solution to these problems. It has been tested with VS2008 and CygWin g++ 4.5.0.

Using the Code

Using the code is simple; just include theSmartEnum.h file in your project (maybe in yourstdafx.h), and then declare yourenums with the macros provided inSmartEnum.h, like this:

BEGIN_SMART_ENUM(MyEnum)  ENUM_MEMBER(member1)  ENUM_MEMBER(member2)END_SMART_ENUM(MyEnum)

You can place thisenumdeclaration anywhere, inside class declarations and namespaces as well as you can do with C++enums. With the aboveenumdeclaration, the following code snippets demonstrate how thisenumsolves the problems that are present when using C++enums.

Using yourenummembers:

 MyEnum e = MyEnum::member1;

Iterating through the members of theenum:

for (MyEnum i=MyEnum::FIRST; i<MyEnum::LAST; ++i)    printf("%d. MyEnum::%s\n", (int)i, i.ToString());

Now you also have some predefined constants and methods in theMyEnum "namespace", these are:

MyEnum::FIRSTMyEnum::LAST == MyEnum::COUNT == MyEnum::INVALID

You also have some useful methods:

staticconstchar* MyEnum::ToString(const MyEnum& e);constchar* MyEnum::ToString()const;static MyEnum MyEnum::FromString(constchar* s);staticbool MyEnum::IsValid(const MyEnum& e);bool MyEnum::IsValid()const;// pre- and postfix -- and ++ operators required to iterate

Other useful methods can be added that are required by your project (e.g.:Serialize).

A cool thing is that thisenumis automatically initialized toMyEnum::INVALID so as to make it easier to avoid the common error of leaving anenumuninitialized.

When a program has manyenums with similar member names, programmers can easily make the mistake of comparing twoenumvalues of different types. This results in syntactically valid but buggy C++ code that actually compiles, maybe with a warning message. A C++enumcan also be compared with C++ integers. A smartenumsubmitted in this article can normally be compared only to the same type; you have to cast it to a primitive integral type if you want to do otherwise.

Disadvantages

The solution has some limitations; let's go through them:

  • The value of theenumis stored in a primitive C++ type (char) that makes debugging more difficult. To overcome this, I put in a (const char*) that always points to the name of the member when compiled in debug mode, thus making the size of theenumdifferent in Debug/Release builds.
  • The underlying template metaprogram limits the number ofenummembers to32.
  • These macros generate code that compile much slower than a normal C++enum.
  • Currently,FromString() is O(n); it could be made O(log(n)). Doing so would bring on thread safety issues, so for now, I've chosen this simpler solution.
  • The members cannot have custom values as with regular C++enums.

History

  • 13 November, 2010: Initial release

License

This article, along with any associated source code and files, is licensed underThe Code Project Open License (CPOL)

About the Author

pasztorpisti

Software Developer

Hungary Hungary

Member


loading...
Sign Up to vote  PoorExcellent
Add a reason or comment to your vote:x
Votes of 3 or less require a comment

Comments and Discussions

 
 RefreshFirstPrevNext
GeneralMy vote of 5memberHarrison H5:44 15 Dec '10  
GeneralRe: My vote of 5memberpasztorpisti13:13 15 Dec '10  
GeneralMy vote of 4memberJoxemi0:17 18 Nov '10  
GeneralRe: My vote of 4memberpasztorpisti1:53 18 Nov '10  
NewsEnum to String and Vice Versa in C++memberFrancisXavier20:00 17 Nov '10  
GeneralRe: Enum to String and Vice Versa in C++memberpasztorpisti1:58 18 Nov '10  
GeneralRe: Enum to String and Vice Versa in C++memberFrancisXavier2:34 22 Nov '10  
GeneralRe: Enum to String and Vice Versa in C++memberpasztorpisti2:55 22 Nov '10  
GeneralMy vote of 2memberbobyx823:02 16 Nov '10  
GeneralYour choice of 'constant' namesmemberStefan6323:27 15 Nov '10  
GeneralRe: Your choice of 'constant' namesmemberpasztorpisti1:58 16 Nov '10  
GeneralMy vote of 5memberKirill Kovalev22:05 14 Nov '10  
Last Visit: 19:00 31 Dec '99     Last Update: 23:52 13 Dec '111

General General   News News   Suggestion Suggestion   Question Question   Bug Bug   Answer Answer   Joke Joke   Rant Rant   Admin Admin   

Permalink |Advertise |Privacy |Mobile
Web01 |2.5.111208.1 |Last Updated 14 Nov 2010
Article Copyright 2010 by pasztorpisti
Everything elseCopyright ©CodeProject, 1999-2011
Terms of Use
Layout:fixed|fluid

See Also...
The Daily Insider

[8]ページ先頭

©2009-2025 Movatter.jp