我陷入了 C++ 的概念问题:
我创建了一个 Pool 模板类,它的功能与 std::list 几乎相同,但只存储对象,并称自己为构造函数,带有放置 new 和存储对象的析构函数。
然后我创建了一个具有 getObjectWithClass 模板方法的 ObjectAllocator 类。我想让这个类像一个接口,这样我就可以有一个 PoolObjectAllocator 子类,它充当 ObjectAllocator 和 Pool 模板类之间的桥梁。
但是没有办法将 getObjectWithClass 创建为虚拟的,因为这是一个模板方法。
template <class T>
class Pool {
...
public:
T& getFreeObject();
...
}
class ObjectAllocator {
public:
template <class T> T* getObjectWithClass(); // I need this method to be virtual
};
class PoolObjectAllocator : public ObjectAllocator {
std::map<int, void *> pools;
public:
template <class T> T* getObjectWithClass() {
int type = T::GetType();
Pool<T> *pool;
if (this->pools.find(type) == this->pools.end()) {
pool = new Pool<T>();
pools[type] = pool;
} else {
pool = static_cast<Pool<T> *>(pools[type]);
}
return &pool->getFreeObject();
};
};
// Later in the program :
ObjectAllocator *objectAllocator = myObject.getObjectAllocator();
objectAllocator->getObjectWithClass<OneClass>();
// Because the above line call a non virtual method, the method called is ObjectAllocator::getObjectAllocator and not PoolObjectAllocator::getObjectAllocator even if the objectAllocator is a PoolObjectAllocator.
我找不到让这个工作的方法,有人可以帮助我吗?谢谢