gpt4 book ai didi

c++ - 将命令模式、工厂模式和模板混合在一起......

转载 作者:行者123 更新时间:2023-11-28 03:33:09 27 4
gpt4 key购买 nike

我已经问过了a similar question here ,但是我并没有真正得到我想要的答案,因为我的问题表述不当而且示例也很糟糕。所以我再试一次,希望有更好的解释和更好的代码。

下面的代码已经去掉了不必要的细节,但它可以工作。问题是,如果可能的话,我想使用模板参数推导来简化模板化函数调用。

我有一个创建命令的工厂。要创建一个命令,我使用这样的调用:

mCommandFactory.createCommand<
DoSomeStuff,
ParameterType1,
ParameterType2,
ParameterType3,
ParameterType4
>
(std:string("some description"),
parameter1,
parameter2,
parameter3,
parameter4);

您可能已经猜到了,parameter1 类型是 ParameterType1,依此类推...。

现在,如果我们看一下命令的定义 - DoSomeStuff- 本身:

class DoSomeStuff : public UndoableCommand< ParameterType1 , ParameterType2, ParameterType3 , ParameterType4 >
{
public:
DoSomeStuff(... /* arguments which are needed for precessing the command and undoing it*/ );
~DoSomeStuff() throw();
void executeImpl();
void undoImpl();

protected:
... /* members which are needed for precessing the command and undoing it*/
};

如您所见,ParameterTypeN 信息已经在 DoSomeStuff 声明中。

我想知道是否有可能以某种方式用更简单的方法替换上面的 createCommand 调用:

mCommandFactory.createCommand<DoSomeStuff>
(std:string("some description"),
parameter1,
parameter2,
parameter3,
parameter4);

这是 CommandFactory 代码:

    class CommandFactory
{
private:
// some stuff used to initialize objects created by this factory

public:
CommandFactory(...) : ... /* members initialization */

{
}


template <class CommandType, typename P1, typename P2, typename P3, typename P4>
void createCommand(juce::String& description,P1 p1, P2 p2, P3 p3, P4 p4)
{
Undoable* cmdPtr = new CommandType(p1, p2, p3, p4);
...
// init cmdPtr

(*cmdPtr)();
}

基本上,重点是将复杂性转移到 CommandFactory 内部,以保持“客户端代码”(对 createCommand 的调用)尽可能简单和简短。

有什么想法吗?

最佳答案

不确定我是否正确理解了问题,但这应该可行。

template<typename ParameterType1 , typename ParameterType2, typename ParameterType3 , typename ParameterType4>
class UndoableCommand
{
public:
UndoableCommand(ParameterType1 p1, ParameterType2 p2, ParameterType3 p3, ParameterType4 p4)
{}
};

class DoSomeStuff : public UndoableCommand< int ,double, std::string , int>
{
public:
DoSomeStuff(int p1, double p2, std::string p3, int p4)
:UndoableCommand(p1,p2,p3,p4)
{}
};

class CommandFactory
{
public:
CommandFactory()
{}

template <class CommandType, typename P1, typename P2, typename P3, typename P4>
void createCommand( std::string& description,P1 p1, P2 p2, P3 p3, P4 p4)
{
UndoableCommand<P1,P2,P3,P4> * cmdPtr = new CommandType(p1, p2, p3, p4);

}
};

这样使用

CommandFactory fact;
fact.createCommand<DoSomeStuff>(std::string("description"),1,2.0,std::string("3"),4);

关于c++ - 将命令模式、工厂模式和模板混合在一起......,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11972818/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com