c++ 成员函数成员函数指针 委托 封装成对象

xiaoxiao2021-02-28  52

struct ICommand { virtual bool execute(const string& args)=0; }; map<string, ICommand*> cmds; class SaveCommand : public ICommand { virtual bool execute(const string& args) { cout << "save command\n"; } }; cmds["save"] = new SaveCommand ; cmds["load"] = new LoadCommand ; 这些可以工作,但是类搞得比较多了,一个命令一个类哦 我是否可以把类的成员函数给搞到 cmds 里呢? 比如 class Model { public: bool Copy(const string& args); bool Paste(const string& args); }; 我想 cmds["copy"] = &Model::Copy; cmds["Paste"] = &Model::Paste; 嗯,它不能通过编译 我用成员函数指针,再来个中间类吧 class ModelCmdDelegate : public ICommand { public: virtual bool execute(const string& args) { return (m->*exe)(args); } typedef bool (Model::ExeFunc)(const string& args); ExeFunc exe; Model* m; }; Model m; ModelCmdDelegate* copycmd = new ModelCmdDelegate; copycmd->m = &m; copycmd->exe = &Model::Copy; cmds["copy"] = copycmd ; ModelCmdDelegate* pastecmd = new ModelCmdDelegate; pastecmd->m = &m; pastecmd->exe = &Model::Paste; cmds["paste"] = pastecmd ; 这样可以解决问题了 我还可以写成模板,这样把各种类的成员函数都加进来 就方便多了 template<typename clsname> class CmdDelegate : public ICommand { typedef bool (clsname::ExeFunc)(const string& args); CmdDelegate<clsname*>(ExeFunc e, clsname* o) : obj(o), exe(e) {} public: virtual bool execute(const string& args) { return (obj->*exe)(args); } ExeFunc exe; clsname* obj; }; CmdDelegate<model*> cd = new CmdDelegate<model*>(&Model::Paste, &m); cmds["paste"] = cd;

转载请注明原文地址: https://www.6miu.com/read-53277.html

最新回复(0)