c++ - 泛化一个函数

标签 c++ c++11 visual-c++

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

 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/

相关文章:

c++ - SFINAE,是可调用的特征

c++ - 使用 C++ 获取 %APPDATA% 路径

c++ - wxFrame 中的透明 wxPanel 成员

c++ - 创建单链表时正确设置指针的问题

c++ - 为什么通过以下方式将ID传递给线程很不好?

c++ - 区分 C++11 原始类型名称和 typedef 名称?

c++ - 如何从 C++ 中的两个 vector 中获取相同的对

algorithm - 动态规划

c++ - 为什么找不到 DirectX 模板?

c++ - 编译器和链接器如何处理类和函数