GCC在'<'标记错误之前预期模板名称

时间:2015-06-09 20:31:26

标签: c++ templates ubuntu inheritance g++

我浏览了其他类似的主题,但未找到问题的答案......

下面的代码说明了这种情况。基类和派生类:

Base.hpp

namespace test {

template<class T>
class Base {
public:
    Base();
    virtual ~Base();
};

}

Base.cpp

#include "Base.hpp"

namespace test {

template<class T>
Base<T>::Base() {
    // TODO Auto-generated constructor stub

};

template<class T>
Base<T>::~Base() {
    // TODO Auto-generated destructor stub
};

}

Derived.hpp

namespace test {

class Derived : public Base<int> {
public:
    Derived();
    virtual ~Derived();
};

} /* namespace aeirtuaccess */

Derived.cpp

#include "Derived.hpp"

namespace test {

Derived::Derived() {
    // TODO Auto-generated constructor stub

};

Derived::~Derived() {
    // TODO Auto-generated destructor stub
};

}

当我使用Coliru - see it in action here编译此代码时,它工作正常,但是当我使用g ++进入我的Ubuntu环境时,我遇到以下错误:

>g++  Base.cpp Derived.cppIn file included from Derived.cpp:2:0:
Derived.hpp:3:28: error: expected template-name before ‘<’ token
 class Derived : public Base<int> {
                            ^
Derived.hpp:3:28: error: expected ‘{’ before ‘<’ token
Derived.hpp:3:28: error: expected unqualified-id before ‘<’ token
Derived.cpp:6:18: error: invalid use of incomplete type ‘class test::Derived’
 Derived::Derived() {
                  ^
In file included from Derived.cpp:2:0:
Derived.hpp:3:7: error: forward declaration of ‘class test::Derived’
 class Derived : public Base<int> {
       ^
Derived.cpp:11:19: error: invalid use of incomplete type ‘class test::Derived’
 Derived::~Derived() {
                   ^
In file included from Derived.cpp:2:0:
Derived.hpp:3:7: error: forward declaration of ‘class test::Derived’
 class Derived : public Base<int> {

编译器之间有什么区别吗?我应该使用特定的g ++标志或版本吗?在我的Ubuntu环境中还有其他一些我需要做的事情吗?

1 个答案:

答案 0 :(得分:5)

Derived.hpp中,您需要添加:

#include "Base.hpp"

在顶部。否则,编译器在编译此文件时不知道Base引用了什么。