kal
kal

Reputation: 29421

Converting strings to enum in C++?

Strings to enum in C#, how do you normally converting strings to enum in C++. Any helper function that you use, is it a good idea to do this.

Upvotes: 1

Views: 621

Answers (3)

Andrii Syrokomskyi
Andrii Syrokomskyi

Reputation: 423

#include <EnumString.h>

from http://codeproject.com/Articles/42035/Enum-to-String-and-Vice-Versa-in-C and after

enum FORM {
    F_NONE = 0,
    F_BOX,
    F_CUBE,
    F_SPHERE,
};

insert

Begin_Enum_String( FORM )
{
    Enum_String( F_NONE );
    Enum_String( F_BOX );
    Enum_String( F_CUBE );
    Enum_String( F_SPHERE );
}
End_Enum_String;

Work fine, if values in enum are not dublicate.

Example in code

enum FORM f = ...
const std::string& str = EnumString< FORM >::From( f );

and vice versa

assert( EnumString< FORM >::To( f, str ) );

Upvotes: 0

SAMills
SAMills

Reputation: 456

I reviewed this approach awhile ago - available via Code Project

Upvotes: 2

Crashworks
Crashworks

Reputation: 41482

You will probably need to use a std::map or hash_map data structure.

Upvotes: 0

Related Questions