With macro, you can write a beautiful solution for problem such as this:
- Define an enum such that its value can be converted into its string representation and vice-versa.
Suppose, you want to define an enum called period
whose members are one
, five
, ten
, fifteen
and thirty
. Then here is how you do it:
First create a header file called period_items.h
as:
//period_items.h
//Here goes the items of the enum
//it is not a definition in itself!
E(one)
E(five)
E(ten)
E(fifteen)
E(thirty)
then create another header file called period.h
as:
//period.h
#include <string>
//HERE goes the enum definition!
enum period
{
#define E(item) item,
#include "period_items.h" //it dumps the enum items in here!
#undef E
period_end
};
period to_period(std::string const & name)
{
#define E(item) if(name == #item) return item;
#include "period_items.h"
#undef E
return period_end;
}
Now you can simply include period.h
and use to_period
function. :-)
You could also add this function to period.h
as:
std::string to_string(period value)
{
#define E(item) if(value == item) return #item;
#include "period_items.h"
#undef E
return "<error>";
}
Now, you could write this:
#include "period.h"
period v = to_period("fifteen"); //string to period
std::string s = to_string(v); //period to string
Why this solution is beautiful?
Because now if you want to add few more members to the enum, all you have to do is to add them to period_items.h
as:
//period_items.h
//Here goes the items of the enum
//it is not a definition in itself!
E(one)
E(five)
E(ten)
E(fifteen)
E(thirty)
E(fifty) //added item!
E(hundred) //added item!
E(thousand) //added item!
And you're done. to_string
and to_period
will work just fine, without any modification!
--
I took this solution from my solution to another problem, posted here: