Get the App
SLTechnology News&Howtos  ›  Development  › 

How to solve the problem of conversion from enumerated values to enumerated names in cantilever 11

Shulou Source: shulou.com Published: 2022-06-01 06:05:49 10月03日 Update

This article mainly introduces how to solve the problem of how to realize the conversion from enumerated values to enumerated names. This article is very detailed and has a certain reference value. Interested friends must finish reading it!

Effect ENUM_DEFINE (Color, Red, Blue,) EnumHelper (Color::Red)-> "Red" EnumHelper (Color::Red, std::toupper)-> "RED" key technology _ _ VA_ARGS__

_ _ VA_ARGS__ implements macros with variable parameters.

# define XXX (type,...) Enum class type {_ _ VA_ARGS__}

XXX (Color, Red, Blue) is equivalent to:

Enum class Color {Red, Blue}; # _ _ VA_ARGS__

# _ _ VA_ARGS__ converts the variable parameters of a macro to a string.

# define XXX (type,...) # _ _ VA_ARGS__

XXX (Color, Red, Blue) is equivalent to "Red, Blue"

The ability to execute code outside a function

Outside the function, you can execute a function by defining a global variable. It is important to note that variable initialization cannot normally be done in the header file unless static or const is added.

Const int temp = initialize ()

In addition, if multiple code files # include the header file, multiple variables will be generated, that is, the temp variables obtained in different code files are not the same. Correspondingly, the initialize function is called multiple times.

Static variables of template functions

The static variable of the function can be used to hold the mapping of enumerated values to enumerated strings, while template functions that use enumerated types as template parameters can directly provide a mapping container for each enumeration.

Key code templatestring EnumHelper (T key, const std::function processor = nullptr, const char* pszName = NULL) {static_assert (std::is_enum_v, _ _ FUNCTION__ "'s key need an enum"); static map smapmapName; if (nullptr! = pszName) {smapNamekey = pszName;} std::string res = ""; auto it = s_mapName.find (key) If (it! = s_mapName.end () res = it- > second; if (nullptr! = processor) std::transform (res.begin (), res.end (), res.begin (), processor); return res;} template size_t analystEnum (T enumClass, const char* pszNames) static_assert (std::is_enum_v, _ FUNCTION__ "'s enumClass need an enum"); cout

Tags: Function variable code file parameter template problem key content multiple character string equivalence article static variable different value global interest Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Shulou Information Redmi vpn macOS