[英]How to reuse table that would be based on different types in C++?
I have problems to re-use parts of C++ code.我在重用部分 C++ 代码时遇到问题。
I need to register a number of objects in a table with the following code:我需要使用以下代码在表中注册多个对象:
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));
}
However, for my new case, I need to fill the table with ojbects of type SpecificResource.但是,对于我的新案例,我需要用特定资源类型的对象填充表。 How can I approach this new situation while still making use of m_resourceTable?
如何在仍然使用 m_resourceTable 的同时处理这种新情况?
EDIT:编辑:
The strategy of inheritance seems to work, however, a new issue pops up: inheritance 的策略似乎行得通,但是,弹出一个新问题:
class DifferentResource :
public GeneralDifferentResource,
public SpecificResource
GeneralDifferentResource inherites from GeneralResource. GeneralDifferentResource 继承自 GeneralResource。 Now, we have some methods result into ambigious access problems.
现在,我们有一些方法会导致模棱两可的访问问题。 How to let DifferentResource first resolve methods from GeneralDifferentResource and second from SpecificResource (to resolve ambiguity)?
如何让 DifferentResource 首先从 GeneralDifferentResource 解析方法,然后从 SpecificResource 解析方法(以解决歧义)? How ambiguity can be resolved is explained here: StackOverflow Question on Ambiguity
这里解释了如何解决歧义: StackOverflow Question on Ambiguity
However, for my new case, I need to fill the table with objects of type SpecificResource.
但是,对于我的新案例,我需要使用 SpecificResource 类型的对象填充表。
Derive SpecificResource
from GeneralResource
and make it's destructor virtual:从
GeneralResource
派生SpecificResource
并使其成为虚拟的析构函数:
class GeneralResource
{
virtual ~GeneralResource() {}
//..
};
class SpecificResource : public GeneralResource
{
//...
};
If GeneralResource
is not that general, then define an AbstractResource
from which you can derive all other resource classes:如果
GeneralResource
不是那么通用,则定义一个AbstractResource
,您可以从中派生所有其他资源类:
class AbstractResource
{
virtual ~AbstractResource() {}
//...
};
class GeneralResource : public AbstractResource
{
//..
};
class SpecificResource : public AbstractResource
{
//...
};
And if you follow this approach, then use this map:如果你遵循这种方法,那么使用这个 map:
typedef map<ResourceType_t, AbstractResource*> ResourceTable_t;
Have SpecificResource inherit from GeneralResource, if it makes sense for you.如果对您有意义,请让 SpecificResource 从 GeneralResource 继承。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.