使用函式指標和map載入不確定配置檔案的實現
阿新 • • 發佈:2018-11-19
#include<iostream> #include<string> #include<map> typedef void (*pFunc)(); //用於指向具體載入配置檔案的函式 using namespace std; enum TYPE //定義兩個配置檔案,以它作為map的key { CHARGE, CHARGESWITCH }; struct configInfo { unsigned int lastVesion; //儲存上一個版本號 string configName; //配置檔名稱 string configMod; //配置檔案對應的版本檔名稱 pFunc pfunc; //載入該配置的函式指標 }; map<TYPE,configInfo*> *configMap = new map<TYPE,configInfo*>(); void loadCharge() { cout<<"load Charge success!"<<endl; } void loadChargeSwitch() { cout<<"load ChargSwitch success!"<<endl; } void Init() //初始化,完成map最初的資料匯入 { configInfo *charge = new configInfo; charge->lastVesion = 0; charge->configName = "charge.cfg"; charge->configMod = "charge_mod.cfg"; charge->pfunc = &loadCharge; //指向charge配置 (charge->pfunc)(); configMap->insert(pair<TYPE,configInfo*>(CHARGE,charge)); configInfo *chargeswitch = new configInfo; chargeswitch->lastVesion = 0; chargeswitch->configName = "chargeswitch.cfg"; chargeswitch->configMod = "chargeswitch_mod.cfg"; chargeswitch->pfunc = &loadChargeSwitch; //指向chargeswitch配置 (chargeswitch->pfunc)(); configMap->insert(pair<TYPE,configInfo*>(CHARGESWITCH,chargeswitch)); } int GetCurVersion() { return 1; } bool ExecuteOneTime(TYPE e) { map<TYPE,configInfo*>::iterator iter = configMap->find(e); if(iter == configMap->end()) //map中沒有該配置返回false return false; int curVersion = GetCurVersion(); if(curVersion <= iter->second->lastVesion) //如果當前版本不是最新的,就選擇不載入該配置 return false; (iter->second->pfunc)(); //載入配置 return true; } int main() { Init(); ExecuteOneTime(CHARGE); ExecuteOneTime(CHARGESWITCH); return 0; } 執行結果如下: <img src="https://img-blog.csdn.net/20160922004402276?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" width="261" height="74" alt="" /> 該程式可以拓展,如某個應用同時要載入幾個配置檔案,但不確定載入哪個,可以給每個配置設定一個mod檔案,mod檔案可以存入版本號,有幾個配置就呼叫幾個ExecuteOneTime, ExecuteOneTime中根據mod中的版本號和之前版本進行對比,再決定是否需要載入該配置。