C++枚举与字符串之间的转换

template
struct SEnumName
{
	static const char* List[];
};
enum ProgLang
{
	e_cpp,
	e_java,
	e_csharp
};
const char* SEnumName::List[] =
{
	"cpp",
	"java",
	"csharp"
};

enum ScriptLang
{
	e_lua,
	e_actionscript,
	e_javascript
};
const char* SEnumName::List[] =
{
	"lua",
	"actionscript",
	"javascript"
};
template
EnumType ConvertStringToEnum(const char* pStr)
{
	EnumType fooEnum = static_cast(-1);
	int count = sizeof(SEnumName::List) /
		sizeof(SEnumName::List[0]);
	for (int i = 0; i < count; ++i)
	{
		const char *ch = SEnumName::List[i];
		if (!abs(strcmp( pStr, SEnumName::List[i])))
		{
			fooEnum = static_cast(i);
			break;
		}
	}
	return fooEnum;
}
template
const char * ConvertEnumToString(EnumType enumPara)
{
	return SEnumName::List[enumPara];
}
int _tmain(int argc, _TCHAR* argv[])
{
	
	ProgLang fooEnum = ConvertStringToEnum("cpp");
	cout << "fooEnum:" << fooEnum << endl;

	ScriptLang fooEnum1 = ConvertStringToEnum("javascript");
	cout << "fooEnum1:" << fooEnum1 << endl;

	const char *str = ConvertEnumToString(e_cpp);
	cout << "fooEnum str:" << str << endl;

	return 0;
}
如题:枚举类型与字符串之间的转换。

你可能感兴趣的:(C++枚举与字符串之间的转换)