c++11?實(shí)現(xiàn)枚舉值到枚舉名的轉(zhuǎn)換問題
效果
ENUM_DEFINE ( Color,
Red,
Blue,
)
EnumHelper(Color::Red) -> "Red"
EnumHelper(Color::Red, std::toupper) -> "RED"關(guān)鍵技術(shù)
__VA_ARGS__
__VA_ARGS__ 實(shí)現(xiàn)了可變參數(shù)的宏。
#define XXX(type, ...) enum class type { __VA_ARGS__ };XXX(Color, Red, Blue) 等價(jià)于:
enum class Color
{
Red,
Blue
};#__VA_ARGS__
#__VA_ARGS__ 可將宏的可變參數(shù)轉(zhuǎn)為字符串。
#define XXX(type, ...) #__VA_ARGS__
XXX(Color, Red, Blue) 等價(jià)于:"Red, Blue"
在函數(shù)外執(zhí)行代碼的能力
在函數(shù)體外,可以通過定義全局變量來執(zhí)行一個(gè)函數(shù)。需要注意的是,頭文件中正常是不能進(jìn)行變量初始化的,除非加上 static 或者 const。
const int temp = initialize();
另外,如果多個(gè)代碼文件 #include 了該頭文件,會(huì)產(chǎn)生多個(gè)變量,即在不同代碼文件取得的 temp 變量不是同一個(gè)。與之對(duì)應(yīng),initialize 函數(shù)也會(huì)調(diào)用多次。
模板函數(shù)的靜態(tài)變量
函數(shù)的靜態(tài)變量可以用于存放枚舉值到枚舉字符串的映射,而將枚舉類型作為模板參數(shù)的模板函數(shù),則可以直接為每種枚舉提供了一個(gè)映射容器。
關(guān)鍵代碼
template<typename T>
string EnumHelper(T key, const std::function<char(char)> processor = nullptr, const char* pszName = NULL)
{
static_assert(std::is_enum_v<T>, __FUNCTION__ "'s key need a enum");
static map<T, string> s_mapName;
if (nullptr != pszName)
{
s_mapName[key] = 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 <class T>
size_t analystEnum(T enumClass, const char* pszNames)
static_assert(std::is_enum_v<T>, __FUNCTION__ "'s enumClass need a enum");
cout << "analystEnum: " << pszNames << endl;
if (nullptr != pszNames)
const vector<string>& vecName = split(pszNames, ",");
for (int i = 0; i < vecName.size(); ++i)
{
if (vecName.at(i).size() > 0)
{
EnumHelper((T)(i + 1), nullptr, vecName.at(i).c_str() + (i == 0 ? 0 : 1) );
}
}
return rand();
return rand();
#define ENUM_DEFINE(type, ...) enum class type { placeholder, __VA_ARGS__ }; static const size_t g_uEnumSizeOf##type = analystEnum(type::placeholder, #__VA_ARGS__);到此這篇關(guān)于c++11 實(shí)現(xiàn)枚舉值到枚舉名的轉(zhuǎn)換的文章就介紹到這了,更多相關(guān)c++11 枚舉值到枚舉名的轉(zhuǎn)換內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
如何在Qt中實(shí)現(xiàn)關(guān)于Json?的操作
JSON是一種輕量級(jí)數(shù)據(jù)交換格式,常用于客戶端和服務(wù)端的數(shù)據(jù)交互,不依賴于編程語言,在很多編程語言中都可以使用JSON,這篇文章主要介紹了在Qt中實(shí)現(xiàn)關(guān)于Json的操作,需要的朋友可以參考下2023-08-08
QT網(wǎng)絡(luò)編程Tcp下C/S架構(gòu)的即時(shí)通信實(shí)例
下面小編就為大家?guī)硪黄猀T網(wǎng)絡(luò)編程Tcp下C/S架構(gòu)的即時(shí)通信實(shí)例。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-08-08
C++中g(shù)etline()、gets()等函數(shù)的用法詳解
這篇文章主要介紹了C++中g(shù)etline()、gets()等函數(shù)的用法,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-02-02

