本文介绍了C ++继承和模板无法编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to implement a generic hashlist class using templates and I am trying to inherit from the base class but getting lots of compile errors. Here is my code:

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

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

I am receiving a lot of compile time errors such as:

标记<"之前的预期模板名称预期'('在标记'<'

expected template-name before token '<'expected '(' before token '<'

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

For such a simple task I spent couple of hours and I am super frustrated, does anybody see what I am doing wrong here?

推荐答案

AccountList的构造函数中,这个初始化符对我来说似乎是错误的:

This initaliser in AccountList's constructor looks wrong to me:

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

您应该在BaseHashList本身的构造函数中初始化BaseHashList的成员,始终会显式或隐式调用该成员.

You should initalise the members of BaseHashList inside a constructor of BaseHashList itself, one will always either explicitly or implicitly be called.

此示例已简化,同样是错误的:

This example is simplified and similarly wrong:

struct A {
  int bar;
};

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

(说bar(0)在那里也是错误的)

(saying bar(0) would also be wrong there)

但是您可以获得所需的行为:

However you can get the desired behaviour:

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

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

A的构造函数被调用,并有机会在此处继续初始化其成员.

The constructor of A gets called and given a chance to initalise its members here still.

这篇关于C ++继承和模板无法编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 07:55