GCC expected template-name before ‘<’ token error

9.1k views Asked by At

I´ve browsed other similar topics and did not find an answer to my problem...

The code below illustrates the situation. A Base class and a Derived 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
};

}

When I compile this code with Coliru - see it in action here, it works fine, but when I go to my Ubuntu environment using g++ I´m having the following error:

>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> {

Is there any difference between the compilers ? Should I use a specific g++ flag or version ? Is there something else that I need to do to fix that in my Ubuntu environment ?

1

There are 1 answers

2
Greg Hewgill On BEST ANSWER

In Derived.hpp, you need to add:

#include "Base.hpp"

at the top. Otherwise, the compiler doesn't know what Base refers to when compiling this file.