How to reuse table that would be based on different types in C++?
I have problems to re-use parts of C++ code.
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?
EDIT:
The strategy of inheritance seems to work, however, a new issue pops up:
class DifferentResource :
public GeneralDifferentResource,
public SpecificResource
GeneralDifferentResource inherites from GeneralResource. Now, we have some methods result into ambigious access problems. How to let DifferentRe开发者_运维百科source first resolve methods from GeneralDifferentResource and second from SpecificResource (to resolve ambiguity) ? How ambiguity can be resolved is explained here: StackOverflow Question on Ambiguity
However, for my new case, I need to fill the table with objects of type SpecificResource.
Derive SpecificResource
from GeneralResource
and make it's destructor virtual:
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:
class AbstractResource
{
virtual ~AbstractResource() {}
//...
};
class GeneralResource : public AbstractResource
{
//..
};
class SpecificResource : public AbstractResource
{
//...
};
And if you follow this approach, then use this map:
typedef map<ResourceType_t, AbstractResource*> ResourceTable_t;
Have SpecificResource inherit from GeneralResource, if it makes sense for you.
精彩评论