Re: macro for enum to string?
From: Ahti Legonkov (lego_at_127.0.0.1)
Date: 03/29/04
- Next message: Richard Herring: "Re: Overloaded Constructors"
- Previous message: Jacek Dziedzic: "Re: Design patterns C++"
- In reply to: Jeff Schwab: "Re: macro for enum to string?"
- Next in thread: Default User: "Re: macro for enum to string?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Mon, 29 Mar 2004 18:57:31 +0300
Jeff Schwab wrote:
> TheFerryman wrote:
>
>> can a macro be created that converts the name of an enumeration to a
>> string? Something like:
>>
>> enum{red, green, blue};
>>
>> cout << ENUM_TO_STRING(blue);
>
>
> Why a macro?
>
> enum Color { red, green, blue };
>
> char const* enum_to_string[ ] = { "red", "green", "blue" };
>
> #include <iostream>
>
> int main( )
> {
> std::cout << "Green is represented by the enumerator "
> << enum_to_string[ green ] << ".\n";
> }
#define ENUM_TO_STRING(x) #x
This macro converts the name of an enumeration to string but it is not
limited to enums. And it only converts at compile time. So, this
probably does not suit your needs.
The solution that Jeff proposed works only if the enum values start from
0 and are continuous. To make that more flexible, you should create a map:
#include <iostream>
#include <map>
enum colors { red, green, blue };
enum fruits { apple = 12, orange = 22, banana = 78 };
template <typename Enum>
std::map<int, char const*>& make_map();
std::map<int, char const*> colors_enum_to_string;
std::map<int, char const*> fruits_enum_to_string;
#define ENUM_ITEM(en, item) en##_enum_to_string[item] = #item
template <>
std::map<int, char const*>& make_map<colors>()
{
ENUM_ITEM(colors, red);
ENUM_ITEM(colors, green);
ENUM_ITEM(colors, blue);
return colors_enum_to_string;
}
template <>
std::map<int, char const*>& make_map<fruits>()
{
ENUM_ITEM(fruits, apple);
ENUM_ITEM(fruits, orange);
ENUM_ITEM(fruits, banana);
return fruits_enum_to_string;
}
template <typename Enum>
char const* enum_to_str(Enum e)
{
static std::map<int, char const*>& m = make_map<Enum>();
return m[e];
}
int main()
{
std::cout << "Green is represented by the enumerator "
<< enum_to_str(green) << ".\n";
std::cout << "Banana is represented by the enumerator "
<< enum_to_str(banana) << ".\n";
return 0;
}
Creating map for each enum you create and creating the function to
populate each map is very tiresome and error prone to do by hand. To
make it easier, a script that does it would be a helpful tool.
-- Ahti Legonkov
- Next message: Richard Herring: "Re: Overloaded Constructors"
- Previous message: Jacek Dziedzic: "Re: Design patterns C++"
- In reply to: Jeff Schwab: "Re: macro for enum to string?"
- Next in thread: Default User: "Re: macro for enum to string?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|
|