在C ++中将字符串转换为枚举?

时间:2021-06-04 10:00:52

Strings to enum in C#, how do you normally converting strings to enum in C++. Any helper function that you use, is it a good idea to do this.

要在C#中枚举的字符串,你通常如何在C ++中将字符串转换为枚举。你使用的任何辅助函数,最好这样做。

3 个解决方案

#1


I reviewed this approach awhile ago - available via Code Project

我之前评论过这种方法 - 可以通过Code Project获得

#2


You will probably need to use a std::map or hash_map data structure.

您可能需要使用std :: map或hash_map数据结构。

#3


#include <EnumString.h>

from http://codeproject.com/Articles/42035/Enum-to-String-and-Vice-Versa-in-C and after

来自http://codeproject.com/Articles/42035/Enum-to-String-and-Vice-Versa-in-C之后

enum FORM {
    F_NONE = 0,
    F_BOX,
    F_CUBE,
    F_SPHERE,
};

insert

Begin_Enum_String( FORM )
{
    Enum_String( F_NONE );
    Enum_String( F_BOX );
    Enum_String( F_CUBE );
    Enum_String( F_SPHERE );
}
End_Enum_String;

Work fine, if values in enum are not dublicate.

如果enum中的值不是dublicate,则工作正常。

Example in code

代码示例

enum FORM f = ...
const std::string& str = EnumString< FORM >::From( f );

and vice versa

反之亦然

assert( EnumString< FORM >::To( f, str ) );

#1


I reviewed this approach awhile ago - available via Code Project

我之前评论过这种方法 - 可以通过Code Project获得

#2


You will probably need to use a std::map or hash_map data structure.

您可能需要使用std :: map或hash_map数据结构。

#3


#include <EnumString.h>

from http://codeproject.com/Articles/42035/Enum-to-String-and-Vice-Versa-in-C and after

来自http://codeproject.com/Articles/42035/Enum-to-String-and-Vice-Versa-in-C之后

enum FORM {
    F_NONE = 0,
    F_BOX,
    F_CUBE,
    F_SPHERE,
};

insert

Begin_Enum_String( FORM )
{
    Enum_String( F_NONE );
    Enum_String( F_BOX );
    Enum_String( F_CUBE );
    Enum_String( F_SPHERE );
}
End_Enum_String;

Work fine, if values in enum are not dublicate.

如果enum中的值不是dublicate,则工作正常。

Example in code

代码示例

enum FORM f = ...
const std::string& str = EnumString< FORM >::From( f );

and vice versa

反之亦然

assert( EnumString< FORM >::To( f, str ) );