遍历 C++ 中不同类型的集合 [英] Iterating through collection of different types in C++
问题描述
情况
我有一个模板类 TIppImage
用于 T
类型的图像.我有单例类 CIppMemoryManager
,它可以存储许多不同大小和类型的图像.
I have a template class TIppImage<T>
for image of type T
. I have singleton class CIppMemoryManager
which can store a number of images of different size and type.
class CIppMemoryManager
{
public:
/// ... Singleton interface ...
template<class T> TIppImage<T>* GetImage(width, height);
private:
CIppMemoryManager();
~CIppMemoryManager();
std::map<IppDataType, void*> m_Containers;
};
IppDataType
是枚举,其值对应于实际类型.所有管理都在模板类 TIppImageContainer
中完成.并且此类的所有特化都作为 void*
存储在 m_Containers
中.这不是很好,但至少很简单.
IppDataType
is enum, which values correspond to actual types. All management is done in template class TIppImageContainer<T>
. And all specialization of this class is stored in m_Containers
as a void*
. It's not very good, but it is at least simple.
通过这种方法,我可以简单地实现模板 GetImage
方法,如下所示:
With this approach, I can simply implement template GetImage
method like this:
template<class T> TIppImage<T>* CIppMemoryManager::GetImage(width, height)
{
return reinterpret_cast<TIppImageContainer<T>*>(m_Containers[
TIppTypeTraits<T>::ipp_data_type])->GetImage(width, height);
}
我使用特征类 TIppTypeTraits
从给定类型获取枚举值.
where I'm using traits class TIppTypeTraits<T>
to obtain enum value from given type.
问题
我不能简单地实现像构造函数这样的非模板方法.我需要明确处理所有可能的类型:
I cannot simply implement non-template methods like constructor. I need to explicitly handle all possible types:
CIppMemoryManager::CIppMemoryManager()
{
m_Containers[ipp8u] = new CIppImageContainer<Ipp8u>;
m_Containers[ipp8s] = new CIppImageContainer<Ipp8s>;
m_Containers[ipp16u] = new CIppImageContainer<Ipp16u>;
m_Containers[ipp16s] = new CIppImageContainer<Ipp16s>;
...
}
更糟糕的是,对于析构函数,我还需要处理 void*
:
Worse, for destructor I also need to deal with void*
:
CIppMemoryManager::~CIppMemoryManager()
{
delete reinterpret_cast<TIppImageContainer<Ipp8u>*>(m_Containers[ipp8u]);
delete reinterpret_cast<TIppImageContainer<Ipp8s>*>(m_Containers[ipp8s]);
delete reinterpret_cast<TIppImageContainer<Ipp16u>*>(m_Containers[ipp16u]);
delete reinterpret_cast<TIppImageContainer<Ipp16s>*>(m_Containers[ipp16s]);
...
}
所以,问题是:
a) 有没有办法遍历不同类型的集合?此处不能使用traits 类,因为函数是非模板的.
a) Is there some way to iterate through collection of different types? Cannot use traits class here since function is non-template.
b) 有没有更好的方法来存储容器集合 - 不同类型的对象?当它们只是通用模板类的不同特化时,容器本身非常简单.
b) Is there some better way to store collection of containers - objects of different type? When they are just a different specialization of common template class, containers itself are pretty simple.
推荐答案
多态 CIppImageContainer
(让它们共享一个公共基类)和智能指针有什么问题?
What's wrong with polymorphic CIppImageContainer<T>
(make them all share a common base class) and a smart pointer ?
或者某种boost::variant
?
这篇关于遍历 C++ 中不同类型的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!