开发者

Templates: I need to learn these better? Why am i getting errors

开发者 https://www.devze.com 2023-03-02 05:01 出处:网络
I am working on someone elses code that is no longer around and it is old CodeWarrior Code. XCode complains about this:

I am working on someone elses code that is no longer around and it is old CodeWarrior Code. XCode complains about this:

template <class listClass,class itemClass>
void FxStreamingObjectList<listClass,itemClass>::StreamOut(FxStream *stream)
{
    if (listClass::size())
    {
        stream->PutSeparator();
        stream->PutString(mFieldName.c_str());
        stream->PutSeparator();
        stream->PutBeginList();
        stream->Indent(+1);

        listClass::iterator iter;

        for (iter=listClass::begin(); iter != listClass::end(); iter++)
        {
            stream->PutSeparator();
            stream->PutString( (*iter)->GetClassID() );
        }

            (*iter)->StreamOut(stream);
        }
        stream->Indent(-1);
        stream->PutSeparator();
        stream->PutEndList();
        stream->PutSeparator();
}

}

I get errors on listClass::iterator iter; and for (iter=listClass::begin(); iter != listClass::end(); iter++) that are:

error: expected `;' before 'iter'
error: 'iter' was not declared in this scope

Other places in the same .h, same types of template declarations I get errors开发者_C百科 like:

error: dependent-name 'listClass::iterator' is parsed as a non-type, but instantiation yields a type

at:

for (listClass::iterator iter=listClass::begin(); iter != listClass::end(); iter++)

How do I go about solving these errors? I dont know templates all that well so I am confused and not sure where to begin. A good template resource is also appreciated.


The compiler doesn't know until a bit later in the parsing process that the specific listClass for any particular instantiation of FxStreamingObjectList<listClass, itemClass> has a member type called iterator. The name iterator is therefore a "dependent name".

You must hint to the compiler that you expect/require iterator here to be a type, with the typename keyword:

typename listClass::iterator iter;

and:

for (typename listClass::iterator it = listClass::begin(), end = listClass::end(); it != end; ++it)

(BTW, are begin() and end() really static member functions?)

Just another C++ quirk. :)


Officially C++ does not know whether dependent symbols are types or otherwise. To you the programmer listClass::iterator is obviously a type. The compiler needs some help.

The definition of iter should be:

typename listClass::iterator iter


The other answers already answered Why the Error
As for the second part of your the Question: A good template resource is also appreciated

The most definitive book on C++ Templates is:
C++ Templates: The Complete Guide by David Vandevoorde & Nicolai Josuttis

0

精彩评论

暂无评论...
验证码 换一张
取 消