模板函数实例化自定义数据类型的问题

时间:2013-12-19 12:22:58

标签: c++ templates

尝试创建各种数据库实例的对象缓存,以便只存储一个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.

1 个答案:

答案 0 :(得分:0)

看这里

Db<K,V> * lookup_db_ptr = NULL;

然后在

下面
lookup_db_ptr = (Db<string,string> *)mapObjCache[Db_key];

你看到错误吗?