2012-05-11 78 views
1

我想实现一个通用的哈希表类使用模板,我试图从基类继承,但得到大量的编译错误。这里是我的代码:C++继承和模板不编译

#ifndef BASEHASHLIST_H_ 
#define BASEHASHLIST_H_ 

#include <string> 
#include <boost/unordered_set.hpp> 
#include <iostream> 
#include <boost/interprocess/sync/interprocess_semaphore.hpp> 
#include <boost/date_time/posix_time/posix_time.hpp> 



    template <typename T> 
    class BaseHashList 
    { 

    private: 
     boost::interprocess::interprocess_semaphore m_semaphore; 

    protected: 

     boost::unordered_set<T> m_hsHashSet;     
     typename boost::unordered_set<T>::iterator m_hsIter;    
    public: 

     BaseHashList(); 
    }; 

    template <typename T> 
    BaseHashList<T>::BaseHashList():m_semaphore(1){} 

#endif /* BASEHASHLIST_H_ */ 

这里是从基类继承的类:

#ifndef ACCOUNTLIST_H_ 
#define ACCOUNTLIST_H_ 

#include "BaseHashList.h" 

    class AccountList : public BaseHashList<unsigned long> 
    { 
    public: 
     AccountList(std::string p_strFile, unsigned long p_ulMaxAccountNo); 
     ~AccountList(void); 

     int m_iVersion; 
     std::string m_strFilePath; 


    private: 
     unsigned long m_ulMaxAccountNo; 
    }; 


#endif /* ACCOUNTLIST_H_ */ 

,这里是cpp文件:

#include "AccountList.h" 

AccountList::AccountList(std::string p_strFile, unsigned long p_ulMaxAccountNo) 
: BaseHashList<unsigned long>::m_hsHashSet<unsigned long>(), 
    m_iVersion(0), 
    m_strFilePath(p_strFile) 
{ 
    m_ulMaxAccountNo = p_ulMaxAccountNo; 
} 


AccountList::~AccountList(){} 

我收到一个很多编译时错误,如:

预期的标记之前的模板名称'<' 预期“(”前令牌“<”

对于这样一个简单的任务,我花了几个小时,我是超级沮丧,任何人都不会看到我在做什么错在这里?

回答

2

这initaliser在AccountList的构造看起来我错了:

BaseHashList<unsigned long>::m_hsHashSet<unsigned long>() 

你应该initalise的BaseHashList成员BaseHashList本身在构造函数中,一个总是或隐或显地叫。

这个例子被简化,同样错误:

struct A { 
    int bar; 
}; 

struct B : A { 
    B() : A::bar(0) {} 
}; 

(话说bar(0)也将是有错)

但是你可以得到所需的行为:

struct A { 
    A() : bar(0) {} 
    int bar; 
}; 

struct B : A { 
    B() {} // Implicitly calls A::A although we could have explicitly called it 
}; 

的构造A被召集,并有机会让其成员在这里仍然活跃起来。

0

当你从一个模板类继承时,必须将模板指令添加到子类太:

template <typename T> 
class A : public B<T> 

你也有构造函数和方法的定义之前添加模板指令:

template <typename T> 
A<T>::A() : B<T>() {...} 

template <typename T> 
A<T>::~A() {...}