泛化函数

Generalizing a function

本文关键字:函数 泛化      更新时间:2023-10-16

我正在对三个函数中的不同变量执行相同的步骤。

SumPosition_Channel *posChannel;
bool isLoop;
cont->GetPositionChannel(&posChannel);
isLoop = posChannel->getChannelLoop();
checkBoxChannelLoop->setChecked(isLoop);

SumRotation_Channel *rotChannel;
bool isLoop;
cont->GetRotationChannel(&rotChannel);
isLoop = rotChannel->getChannelLoop();
checkBoxChannelLoop->setChecked(isLoop);

SumScaling_Channel *scaChannel;
bool isLoop;
cont->GetScalingChannel(&scaChannel);
isLoop = scaChannel->getChannelLoop();
checkBoxChannelLoop->setChecked(isLoop);

我可以将它们概括为一个函数吗?

我的建议是使用模板,不仅用于显示的代码,还用于GetXChannel函数。

类似的东西

// In the class for "cont"
template<typename T>
T* GetChannel();
// Specialization for SumPosition_Channel
template<>
SumPosition_Channel* GetChannel()
{
SumPosition_Channel* channel = new SumPosition_Channel;
// Other SumPosition_Channel specific initialization...
return channel;
}
// Same for the rest of the channels

如果您不需要任何特定于通道的初始化,那么只需

// In the class for "cont"
template<typename T>
T* GetChannel()
{
return new T();
}

然后,可以从您拥有的代码的模板化函数中轻松调用它:

template<typename T>
T* foo(ContType const* cont, CheckBoxChannelLoopType* checkBoxChannelLoop)
{
T* channel = cont->GetChannel<T>();
checkBoxChannelLoop->setChecked(channel->getChannelLoop());
return channel;
}
如果

"频道"一次只能有一个所有者,我建议使用std::unique_ptr,或者如果可以有多个std::shared_ptr同时所有者,我建议使用,而不是上面示例中所示的原始非拥有指针。

是的,您可以使用模板和重载概念来概括它。

template <typename T>
void func () { // your method Signature here
T *channel;
bool isLoop;
cont->GetChannel(&channel); // overload the GetChannel() in the "cont" class type
isLoop = rotChannel->getChannelLoop();
checkBoxChannelLoop->setChecked(isLoop);
}

现在,您可以使用相应的类型调用该函数。

请记住在每个模板参数类型的"cont"类类型中重载 GetChannel(( 方法。

希望这有帮助,谢谢。

通过重载函数非常简单,特别是如果您没有为这些类设计接口。

void GetChannel(SumPosition_Channel** channel,WhateverTypeThisIs* checkBoxChannelLoop, ContType* cont);
void GetChannel(SumRotation_Channel** channel,WhateverTypeThisIs* checkBoxChannelLoop, ContType* cont);
void GetChannel(GetScalingChannel** channel,WhateverTypeThisIs* checkBoxChannelLoop, ContType* cont);

在每个函数中,只需调用相应的函数。 即

void GetChannel(SumPosition_Channel** channel, WhateverTypeThisIs* checkBoxChannelLoop, ContType* cont)
{
bool isLoop;
cont->GetPositionChannel(&channel);
isLoop = channel->getChannelLoop();
checkBoxChannelLoop->setChecked(isLoop);
}

如果您设计了接口,我建议在实际的 cont 类中重载这些函数,因为这样您需要键入更少的内容。