【问题标题】:GCC expected template-name before ‘<’ token error [closed]GCC 在“<”标记错误之前预期模板名称 [关闭]
【发布时间】:2015-06-09 20:31:25
【问题描述】:

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

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

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

【问题讨论】:

  • 你用的是什么编译器?如果你在每节课结束时修复缺失的; 和双倍的:,它就可以正常工作。
  • 请发布您遇到问题的实际代码。或者至少,请确认您在此处发布的代码具有可以重现的相同问题。否则,这不是一个合法的问题。
  • This is not the code 不是代码,但我们应该弄清楚什么是真实代码,什么是假代码,并将编译器错误与真实代码匹配。投反对票。
  • @Mendez,任何编译器错误可以用少量代码复制。您只需要花时间删除不相关的代码,但仍然发布一个完整的、可编译的、但显示编译器错误的小代码。
  • @Mendez 参见此处:coliru.stacked-crooked.com/a/a7b806349ad43c36 请注意,从您的帖子中提取的这个小样本可以编译并运行。现在取那个小样本并在其中添加会重复您的错误的行。

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


【解决方案1】:

在Derived.hpp中,需要添加:

#include "Base.hpp"

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

【讨论】:

  • 伟大的格雷格。这解决了我的问题。谢谢...
  • @Mendez:不用担心。它在 Coliru 在线编译器上工作的原因是您将所有内容都放在一个源文件中,因此当编译器编译 class Derived 定义时,它已经看到了 Base 定义。对于单独的文件,您必须告诉编译器在哪里查找。
  • 是的,当我看到你的评论时,我得到了这个闪光......
猜你喜欢
  • 2016-03-25
  • 1970-01-01
  • 1970-01-01
  • 2018-06-28
  • 2013-04-10
  • 1970-01-01
  • 2021-09-22
  • 2015-01-19
相关资源
最近更新 更多