【发布时间】:2026-01-21 19:25:01
【问题描述】:
我有一个像这样的对象缓存类:
#include "boost/thread/mutex.hpp"
#include "boost/unordered_map.hpp"
template <typename type1, typename type2>
class objectCache
{
public:
objectCache()
{
IDCounter = 0;
}
~objectCache()
{
for ( it=free_objects.begin() ; it != free_objects.end(); it++ )
delete (*it).second;
for ( it=busy_objects.begin() ; it != busy_objects.end(); it++ )
delete (*it).second;
}
type1* objectCache::Get()
{
boost::mutex::scoped_lock(io_mutex);
if(free_objects.size() > 0)
{
it = free_objects.begin();
type1 *temp = (*it).second;
busy_objects[(*it).first] = temp;
free_objects.erase(free_objects.begin());
return temp;
}
type1 * temp = new type2;
++IDCounter;
busy_objects[IDCounter] = temp;
return temp;
}
void objectCache::Pushback(type1)
{
boost::mutex::scoped_lock(io_mutex);
free_objects[ID] = socket;
it = busy_objects.find(ID);
busy_objects.erase(it);
}
protected:
private:
boost::mutex io_mutex;
long long IDCounter;
boost::unordered_map<long long, type1*> free_objects;
boost::unordered_map<long long, type1*> busy_objects;
typename boost::unordered_map<long long, type1*>::iterator it;
};
class A{
public:
A(int num){
number = num;
}
int number;
};
int main(int argc, char* argv[])
{
objectCache<a, a(1)> intcache;
A* temp = intcache.Get();
cout <<temp->number <<endl;
system("pause");
return 0;
}
我知道“typename type2”是不必要的,但我需要一种方法来将一个类对象传递给模板,该类对象具有带有类 A 参数的构造函数。 或者他们是另一种方式来做到这一点?请帮忙。
【问题讨论】:
-
你能用语言解释你想用你的类 objectCache 实现什么吗?这样,读者就不必从你的代码中“反汇编”这些信息;你可能会得到更好的答案,因为你的问题会更具体。
标签: c++ templates constructor