泛化函数
Generalizing a function
我正在对三个函数中的不同变量执行相同的步骤。
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 类中重载这些函数,因为这样您需要键入更少的内容。
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 如何泛化作用于不同类型的向量的函数?
- 如何在C++中泛化调用函数列表?
- 泛化函数
- 泛化布尔函数以获得更优雅的代码
- 泛化一个函数,该函数返回基于对象和类方法的可调用函数
- 使用模板进行 C++ 函数代码泛化
- c++非成员函数的泛化链
- C++如何泛化类函数参数来处理多种类型的函数指针