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

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;






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值