如何选择带有类型参数的成员变量? [英] How do I select a member variable with a type parameter?
问题描述
我有一个缓存对象,可以缓存许多不同类型的对象,如下所示:
I have a cache object that caches a number of different types of objects, as illustrated below:
class Cache
{
public:
ObjectTable<ObjTypeA> m_objACache;
ObjectTable<ObjTypeB> m_objBCache;
ObjectTable<ObjTypeC> m_objCCache;
};
我目前正在使用缓存的(糟糕)方式是直接访问缓存类属性"m_objACache"和"m_objBCache",如下所示:
The (horrible) way I'm currently using the cache at the moment is directly accessing the cache class properties "m_objACache" and "m_objBCache" like this:
Cache c;
c.m_objACache.getObjectWithid(objectBuffer, 1);
c.m_objACache.getObjectWithid(objectBuffer, 2);
c.m_objBCache.getObjectWithid(objectBuffer, 3);
等.
我想做的是这样的:-
class Cache
{
public:
template <typename T>
void getObjectWithId(T &objectBuffer, int id)
{
ObjectTable<T>.getObjectWithId(objectBuffer, id);
}
};
但是显然这行不通,因为我有"ObjectTable<T>
"的地方,我需要一个变量名,但是我不能模板类变量-那么有什么办法可以做到这一点?还是声明所有变量并按如下方式访问它:
But obviously that does not work because where I have "ObjectTable<T>
" I need a variable name, but I cannot template class variables - so is there a way I can do this? Or is it going to be a case if declaring all of the variables and accessing it like this:
class Cache
{
public:
void getObjectWithId(ObjTypeA &objectBuffer, int id)
{
m_objACache.getObjectWithId(objectBuffer, id);
}
void getObjectWithId(ObjTypeB &objectBuffer, int id)
{
m_objBCache.getObjectWithId(objectBuffer, id);
}
void getObjectWithId(ObjTypeC &objectBuffer, int id)
{
m_objCCache.getObjectWithId(objectBuffer, id);
}
protected:
ObjectTable<ObjTypeA> m_objACache;
ObjectTable<ObjTypeB> m_objBCache;
ObjectTable<ObjTypeC> m_objCCache;
};
似乎很冗长..
ObjectTable可以使用的每个对象类型都有一个通用的基类,因此可能有其他方法可能不可避免地涉及向下转换,但我希望可以找到更好的方法.
Each object type that an ObjectTable can be used for has a common base class, so there could be some other way of doing this that may inevitably involve downcasting, but I'm hoping I can find a better way.
谢谢!
推荐答案
也许像这样吗?
class Cache
{
// An "envelope" type which up-casts to the right ObjectTable<T>
// if we have a type parameter T.
struct ObjectTables : ObjectTable<ObjTypeA>,
ObjectTable<ObjTypeB>,
ObjectTable<ObjTypeC> {};
ObjectTables tables;
public:
template <typename T>
void getObjectWithId(T &objectBuffer, int id)
{
// C++ does the work here
ObjectTable<T> &o=tables;
t.getObjectWithId(objectBuffer, id);
}
};
此外,它很容易扩展.如果需要支持更多类型,只需投入更多的ObjectTables<>.
Also, it's easy to extend. Just throw in more ObjectTables<> if you need to support more types.
这篇关于如何选择带有类型参数的成员变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!