我在我的三个函数中对不同的变量执行相同的步骤。
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
如果您不需要任何 channel 特定的初始化,那么就
// 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
代替上面示例中所示的原始非拥有指针。如果一个“ channel ”一次只能有一个所有者,或者 std::shared_ptr
如果可以同时有多个所有者。
关于c++ - 泛化一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57423842/