繁体   English   中英

如何重用基于 C++ 中不同类型的表?

[英]How to reuse table that would be based on different types in C++?

我在重用部分 C++ 代码时遇到问题。

我需要使用以下代码在表中注册多个对象:

typedef map<ResourceType_t, GeneralResource*>   ResourceTable_t;
ResourceTable_t m_resourceTable;

template<class _Ty1,
class _Ty2> inline
pair<_Ty1, _Ty2> make_pair(_Ty1 _Val1, _Ty2 _Val2)
{   // return pair composed from arguments
return (pair<_Ty1, _Ty2>(_Val1, _Val2));
}


void MainModule::registerResource(ResourceType_t type, GeneralResource* pGeneral)
{
m_resourceTable.insert(make_pair(type, pGeneral)); 
}

但是,对于我的新案例,我需要用特定资源类型的对象填充表。 如何在仍然使用 m_resourceTable 的同时处理这种新情况?


编辑:

inheritance 的策略似乎行得通,但是,弹出一个新问题:

class DifferentResource : 
              public GeneralDifferentResource, 
              public SpecificResource

GeneralDifferentResource 继承自 GeneralResource。 现在,我们有一些方法会导致模棱两可的访问问题。 如何让 DifferentResource 首先从 GeneralDifferentResource 解析方法,然后从 SpecificResource 解析方法(以解决歧义)? 这里解释了如何解决歧义: StackOverflow Question on Ambiguity

但是,对于我的新案例,我需要使用 SpecificResource 类型的对象填充表。

GeneralResource派生SpecificResource并使其成为虚拟的析构函数:

class GeneralResource 
{
    virtual ~GeneralResource() {}
    //..
};

class SpecificResource : public GeneralResource 
{
   //...
};

如果GeneralResource不是那么通用,则定义一个AbstractResource ,您可以从中派生所有其他资源类:

class AbstractResource
{
    virtual ~AbstractResource() {}
    //...  
};
class GeneralResource : public AbstractResource
{
    //..
};
class SpecificResource : public AbstractResource
{
   //...
};

如果你遵循这种方法,那么使用这个 map:

typedef map<ResourceType_t, AbstractResource*>   ResourceTable_t;

如果对您有意义,请让 SpecificResource 从 GeneralResource 继承。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM