看板 C_and_CPP 關於我們 聯絡資訊
經過 上一篇文的心得後 透過boost 改進如下 Device.h----------------------------------------------------- using namespace std; class Device{ public: Device(); virtual void doAddItem(string parameter); virtual void doDelItem(string parameter); virtual void doShowItem(string parameter); virtual void execute(string command,string parameter); protected: int item_number; map<string,boost::function<void (string)>> cmdMap; }; Device.cpp---------------------------------------------------- Device::Device(){ item_number = 0; cmdMap["add"] = boost::bind(&Device::doAddItem,this,_1); cmdMap["del"] = boost::bind(&Device::doDelItem,this,_1); cmdMap["show"]= boost::bind(&Device::doShowItem,this,_1); } void Device::doAddItem(string parameter){ int num = boost::lexical_cast<int>(parameter); item_number += num; } void Device::doDelItem(string parameter){ int num = boost::lexical_cast<int>(parameter); item_number -= num; } void Device::doShowItem(string parameter){ std::cout << item_number << endl; } void Device::execute(string command,string parameter){ boost::function<void (string)> method = cmdMap[command]; if(method) method(parameter); } --------------------------------------------------------------------- 在angel device中只需要再增加一個 twice AngelDevice::AngelDevice(){ cmdMap["twice"] = boost::bind(&AngelDevice::doTwiceItem,this,_1); } demon device中則是增加 half DemonDevice::DemonDevice(){ cmdMap["half"] = boost::bind(&DemonDevice::doHalfItem,this,_1); } main.cpp------------------------------------------------------------ void main(){ AngelDevice device; string command,parameter; while(true){ cin >> command >> parameter; device.execute(command,parameter); } } 結論 : boost 真的是太好用了 連 template也免了 透過這樣的方式可以輕鬆的建好command table並且 讓指定的device收到 "可執行的"命令 就執行,不可執行的就忽略 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 219.70.172.147
loveme00835:(  ̄ c ̄)y▂ξ 神奇的不只這個呢 08/07 16:51
loveme00835:如果你的編譯器支援新標準, 可以用 Initializer lists 08/07 17:12
loveme00835:來初始化 cmdMap 08/07 17:13