#include はファイルの先頭におくことが多いですが、別にどこにあっても使えます。
[Fruits.lst]
X(Apple)
X(Grape)
X(Banana)
-----
こんなファイルを用意して…
#define X(A) A,
enum{
#include "Fruits.lst"
};
#undef X
こうすると、
enum{
Apple,
Grape,
Banana,
};
こう展開されるわけです。
#define X(A) #A,
const char *Fstr[]={
#include "Fruits.lst"
};
#undef X
こんなのを作れば、enumの数値を文字に直すことが出来ます。
printf("%s\n", Fstr[Banana]); → "Banana"
文字列→数値はこんな関数でいけます。
int Fstr2index(const char *str){
for (int i = 0; i < sizeof(Fstr) / sizeof(Fstr[0]); i++){ if (strcmp(str, Fstr[i]) == 0) return i; }
return -1;
}
ただ、文字列→数値を使う機会が多くて数もある場合はmapを使うといいでしょう。
std::map<std::string, int> Fmap;
#define X(A) Fmap[#A] = A;
#include "Fruits.lst"
#undef X
前回のネタとあわせるとprefixやsuffixをつけることが出来ます。
#define X(A) Fruits_##A,
enum{
#include "Fruits.lst"
};
これで、Fruits_Apple, Fruits_Grape, Fruits_Bananaという名前で定義されます。
#define X(A) "Fruits_" #A,
文字列の方はこんな感じです。