c ++继承和模板不编译

时间:2012-05-11 09:22:19

标签: c++ templates inheritance

我正在尝试使用模板实现通用哈希列表类,我试图从基类继承但是会遇到很多编译错误。这是我的代码:

#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(){}

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

令牌之前的预期模板名称&#39;&lt;&#39; 预期&#39;(&#39;在令牌之前&#39;&lt;&#39;

对于这么简单的任务,我花了几个小时,我非常沮丧,有人看到我在做错了吗?

2 个答案:

答案 0 :(得分:2)

AccountList的构造函数中的这个initaliser对我来说是错误的:

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

你应该在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的构造函数被调用,并且仍然有机会在其中成员。

答案 1 :(得分:0)

从模板类继承时,您还必须将模板指令添加到子类:

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

您还必须在构造函数和方法的定义之前添加模板指令:

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

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