请考虑这个 - 可能写得不好 - 的例子:
class Command;
class Command : public boost::enable_shared_from_this<Command>
{
public :
void execute()
{
executeImpl();
// then do some stuff which is common to all commands ...
}
// Much more stuff ...
private:
virtual void executeImpl()=0;
// Much more stuff too ...
};
和 :
class CmdAdd : public Command
{
public:
CmdAdd(int howMuchToAdd);
void executeImpl();
int _amountToAdd;
};
// implementation isn't really important here ....
有了这个,我可以使用以下语法简单地添加一个回调:
boost::shared_ptr<Command> cmdAdd(CmdAdd(someValue));
cmdAdd->execute();
它完美无缺。我的“命令”类做了更多所有命令共有的事情,例如实现撤消、重做、进度报告等,但为了便于阅读,我将其从代码中删除。
现在我的问题很简单:有没有办法重写命令类,以便我可以替换这个调用:
boost::shared_ptr<Command> cmdAdd(CmdAdd(someValue));
cmdAdd->execute();
通过类似的东西:
CmdAdd(someValue); // preferably
or CmdAdd->execute(someValue)
我一直在考虑这个问题,但我有一个概念上的问题:我想模板化我的 Command 类,比如
template <typename R,typename T1, typename T2, ..., typename Tn> class Command
{
R1 execute(T1 p1, ...,Tn pn)
{
return executeImpl(T1 p1, ...,Tn pn);
// then do some stuff which is common to all commands ...
}
}
但显然,这里有一个问题:语法template <typename R,typename T1, typename T2, ..., typename Tn>
不合法 C++ ,AFAIK。
我是否必须编写 n 个版本的命令,例如:
template <typename R> class Command
template <typename R,typename T1> class Command
template <typename R,typename T1, typename T2> class Command
...
等等 ?(甚至不确定这是否真的有效)
还是有另一种更优雅的方式来做到这一点?这里提到的语法在那里有用吗?(函数 f;)
我一直在查看 Loki 的类型列表,他们似乎完成了这项工作。但是我在Boost中找不到任何东西。我在网上看到 boost::mpl 是一个想要用来实现类型列表的工具,但我对 MPL 文档有点困惑?
对此有何见解?雷加兹,D.