There are no standard mechanisms to convert an enumerated one into a string ... however it is possible to achieve that effect.
The first thing is to create a new file, for example Meses.inc
with a content such that:
MES(Enero)
MES(Febrero)
MES(Marzo)
MES(Abril)
MES(Mayo)
MES(Junio)
MES(Julio)
MES(Agosto)
MES(Septiembre)
MES(Octubre)
MES(Noviembre)
MES(Diciembre)
This file will be the base that will allow us to automatically generate all the code we need. We just need to redefine the macro MES
to generate the code we need at each moment. So, to fill in the list:
enum Meses
{
#define MES(x) x,
#include "Meses.inc"
#undef MES
};
With this we get the preprocessor to generate a code such that:
enum Meses
{
Enero,
Febrero,
Marzo,
// ...
};
While to have a function that allows us to convert the values of the enumerated in chain:
std::string MesToString(Meses mes)
{
switch(mes)
{
#define MES(x) case x: return #x;
#include "Meses.inc"
#undef MES
}
return "";
}
The possibilities are endless and, best of all, in the file meses.inc
we can add additional information ... for example text in different languages:
MES(Enero,January)
MES(Febrero,February)
MES(Marzo,March)
MES(Abril,April)
MES(Mayo,May)
MES(Junio,June)
MES(Julio,July)
MES(Agosto,August)
MES(Septiembre,September)
MES(Octubre,October)
MES(Noviembre,November)
MES(Diciembre,December)
Now, to generate the enumerated one we are only interested in the first parameter:
enum Meses
{
#define MES(x,y) x,
#include "Meses.inc"
#undef MES
};
And to convert to string :
std::string MesToString(Meses mes,bool ingles)
{
switch(mes)
{
#define MES(x,y) case x: return ingles ? #y : #x;
#include "Meses.inc"
#undef MES
}
return "";
}
The bad part of using this mechanism is that the IDEs, will not be able to give us information about the values of the enumerated ( intellisense ), but in return we have a very powerful and versatile mechanism that Avoid writing a good number of lines of code. The compilation time will also be noticeably longer.