0
努力創造各種數據庫實例的對象緩存,因此只有一個DB的實例存儲模板函數實例化問題
class objectCache
{
public:
static inline objectCache& getInstance()
{
static objectCache instance;
return instance;
}
template<typename K, typename V>
Db <K,V> * getDbInstance(string &obj_name);
private:
objectCache(){};
objectCache(const objectCache& copy);
objectCache& operator=(const objectCache& copy);
map <string,void *> mapObjCache;
};
template<typename K, typename V>
Db <K,V> *
objectCache::getDbInstance(string &Db_name)
{
Db<K,V> * lookup_db_ptr = NULL;
string Db_key = "Db_";
Db_key += Db_name;
map <string,void *>::iterator it;
it = mapObjCache.find(Db_key);
if ( mapObjCache.end() != it && NULL != mapObjCache[Db_key])
{
lookup_db_ptr = (Db<string,string> *)mapObjCache[Db_key];
return lookup_db_ptr;
}
else
{
try{
lookup_db_ptr = new Db<K,V>(Db_name,O_RDONLY);
}
catch(...){lookup_db_ptr = NULL;}
}
if (lookup_db_ptr)
{
try{
mapObjCache[Db_key] = (void *)lookup_db_ptr;
}
catch(...)
{
delete lookup_db_ptr;
lookup_db_ptr = NULL;
}
}
return lookup_db_ptr;
}
一些定義是如何失敗的,當我想創建自定義結構的對象。
下面的一個工作
db_ptr = (Db<string,string> *) objectCache::getInstance().getDbInstance <string,string> (dbname);
而定製的結構類型,下面的定義失敗
typedef struct
{
float val1;
float val2;
short int test1;
short int test2;
}myData_t;
myData_t myData;
Db<string,myData_t> *db_ptr;
db_ptr = (Db<string,myData_t> *)
objectCache::getInstance().getDbInstance <string,myData_t> (dbname);
有錯誤
error: cannot convert `Db<std::string, std::string>*' to
`Db<std::string, myData_t>*' in assignment.
你不瞭解什麼?錯誤消息非常清楚。你也不是真的想投這些指針。也使用C++風格強制轉換。另外你爲什麼使用單身? – Shoe