Click here to Skip to main content
11,925,292 members (53,074 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


14 bookmarked

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

, 13 Nov 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
An enum with macro + template magic, providing type safety and type info


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 an enum. This problem is usually solved by adding a "last" member to the enum:

enum MyEnum

Another thing that causes headaches is the conversion between an enum value and its string representation. Most people, especially beginners, end up with something like this to be able to perform the conversion:

static const char* ENUM_STRINGS[MyEnum_Last] =

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 the SmartEnum.h file in your project (maybe in your stdafx.h), and then declare your enums with the macros provided in SmartEnum.h, like this:


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

Using your enum members:

MyEnum e = MyEnum::member1;

Iterating through the members of the enum:

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 the MyEnum "namespace", these are:

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

You also have some useful methods:

static const char* MyEnum::ToString(const MyEnum& e);
       const char* MyEnum::ToString() const;
static MyEnum MyEnum::FromString(const char* s);
static bool 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 this enum is automatically initialized to MyEnum::INVALID so as to make it easier to avoid the common error of leaving an enum uninitialized.

When a program has many enums with similar member names, programmers can easily make the mistake of comparing two enum values of different types. This results in syntactically valid but buggy C++ code that actually compiles, maybe with a warning message. A C++ enum can also be compared with C++ integers. A smart enum submitted 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.


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

  • The value of the enum is 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 the enum different in Debug/Release builds.
  • The underlying template metaprogram limits the number of enum members to 32.
  • 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.


  • 13 November, 2010: Initial release


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


About the Author

Software Developer (Senior)
United Kingdom United Kingdom
No Biography provided

You may also be interested in...

Comments and Discussions

GeneralMy vote of 5 Pin
Harrison H15-Dec-10 5:44
memberHarrison H15-Dec-10 5:44 
GeneralRe: My vote of 5 Pin
pasztorpisti15-Dec-10 13:13
memberpasztorpisti15-Dec-10 13:13 
GeneralMy vote of 4 Pin
Joxemi18-Nov-10 0:17
memberJoxemi18-Nov-10 0:17 
NewsEnum to String and Vice Versa in C++ Pin
FrancisXavier17-Nov-10 20:00
memberFrancisXavier17-Nov-10 20:00 
GeneralRe: Enum to String and Vice Versa in C++ Pin
pasztorpisti18-Nov-10 1:58
memberpasztorpisti18-Nov-10 1:58 
GeneralRe: Enum to String and Vice Versa in C++ Pin
FrancisXavier22-Nov-10 2:34
memberFrancisXavier22-Nov-10 2:34 
GeneralRe: Enum to String and Vice Versa in C++ Pin
pasztorpisti22-Nov-10 2:55
memberpasztorpisti22-Nov-10 2:55 
GeneralMy vote of 2 Pin
bobyx8216-Nov-10 3:02
memberbobyx8216-Nov-10 3:02 
GeneralYour choice of 'constant' names Pin
Stefan6315-Nov-10 23:27
memberStefan6315-Nov-10 23:27 
GeneralRe: Your choice of 'constant' names Pin
pasztorpisti16-Nov-10 1:58
memberpasztorpisti16-Nov-10 1:58 
You may be right... C++ is a very free-form language, and every coder has his own style. It fits my naming convention because I never use capitalized names as enum members. You can modify the code to reflect your own taste. Smile | :) I think that C++0x will be backward compatible enough not to cause a conflict. But yea, you are right, the namespace thingy is something that is about to come, but I'm not sure about iteration and the enum <-> string conversion. Anyway, this whole macro/template magic is considered a big HACK to fill in a gap. Laugh | :laugh: I'm coding a prog that extensively uses enum to string conversion for debug purposes and I am also converting from string during serialization. Both of these tasks can cause headache when some other coder guys modify your code and they forgot to adjust the accompanying "static const char* ENUM_NAMES[]" array for an enum. Big Grin | :-D
GeneralMy vote of 5 Pin
Kirill Kovalev14-Nov-10 22:05
memberKirill Kovalev14-Nov-10 22:05 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.151126.1 | Last Updated 14 Nov 2010
Article Copyright 2010 by pasztorpisti
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid