GCC 在“<”标记错误之前期望模板名称

GCC expected template-name before ‘<’ token error

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

下面的代码说明了这种情况。基础 class 和衍生 class:

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 环境中,我还需要做些什么来解决这个问题吗?

Derived.hpp中,您需要添加:

#include "Base.hpp"

在顶部。否则,编译器在编译这个文件时不知道Base指的是什么。