Expected init-declarator compiler-error with G++

Dear fellow programmers,

I fail to get a typedef in a template class to compile, when using G++ 3.4.4 (compiled with 'g++ UnitMyClass.cpp'). But when I use C++ Builder 6's compiler (BCC32) it compiles successfully.

Below are the simplified code and error messages. Note that I already try to tackle the problem with four different syntaxes.

Google didn't give me the answer, I hope you will.

Thanks in advance, Bilderbikkel

[code]
//UnitMyClass.cpp
#include "UnitMyClass.h"
[/code]

[code]
//UnitMyClass.h
#include


template struct MyClass
{
typedef T value_type;
void MyMethod_1() const
{
typedef std::map::const_iterator Iter;
}
void MyMethod_2() const
{
typedef std::map::const_iterator Iter;
}
void MyMethod_3(const T& t) const
{
typedef std::map::const_iterator Iter;
}
void MyMethod_4(const T& t) const
{
typedef std::map::const_iterator Iter;
}
};
[/code]

The errors (for each version of MyMethod) are:
[code]
$ g++ UnitStorage.cpp
In file included from UnitStorage.cpp:5:
UnitStorage.h: In member function `void MyClass::MyMethod_1() const':
UnitStorage.h:15: error: expected init-declarator before "Iter"
UnitStorage.h:15: error: expected `,' or `;' before "Iter"
[/code]

Comments

  • Surprisingly I actually knew that one!

    It's because of GCC being strict with the standard and Borland ain't. You gotta write

    typedef typename std::map::const_iterator Iter;

    However, I don't enough of the C++ standard to explain the details of that.
  • It works! Thanks Lundin!

    See ya, Bilderbikkel
  • The reason is that these typedefs appears in a place where the compiler is uncapable to know what ::const_iterator is.

    The compiler must parse, before any instantiation (before any substitution of the template parameter T), the template MyClass to search syntax errors among other things, but, at that time, since T has no value, the compiler cannot instantiate std::map<T, double>, and thus, it has no means to know what is inside it.

    Keep in mind that each different instantiation of a same template could contain totally diferent things. For example, map<int, double>::const_iterator could be a typedef, but map<double, double>::const_iterator could be a static or constant variable, or the name of a function, or an enum constant (we know that it is a type, but the compiler doesn't).

    So, you have to tell the compiler that what you are expecting is a type, with the keyword typename as Lundin said, because otherwise, it treats your sentence as an expression instead of as a declaration.

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories