【发布时间】:2010-06-27 01:54:24
【问题描述】:
请考虑这个-可能写得不好-示例:
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 个版本的 Command,例如:
template <typename R> class Command
template <typename R,typename T1> class Command
template <typename R,typename T1, typename T2> class Command
...
等等? (甚至不确定这是否真的有效)
或者还有其他更优雅的方法吗? 那里提到的here 的语法有什么用吗? (函数 f;)
我一直在查看 Loki 的类型列表,它们似乎可以胜任。但是我在Boost中找不到任何东西。我在网上读到 boost::mpl 是一个想要用来实现类型列表的工具,但我对 MPL 文档有点困惑?
对此有何见解? 问候, D.
【问题讨论】:
标签: c++ templates boost metaprogramming boost-mpl