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

GCC expected template-name before ‘<’ token error

本文关键字:错误 期望 GCC      更新时间:2023-10-16

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

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

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编译这段代码时,它工作得很好,但是当我使用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指的是什么。