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

  • Post author:
  • Post category:其他


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

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

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

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

	return 0;
}

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



版权声明:本文为ceasadan原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。