Advertisement

Compiler errors for vector of pointers of compile-time defined types

Started by June 07, 2018 09:08 AM
2 comments, last by hkBattousai 6 years, 3 months ago

I'm trying to implement my own tree container. I have written a "TreeContainer.h" template class and I am posting a piece of its content below.

I have defined a type named "ContainerType", because I am planning to test different other core STL container types later. I want the container type to be define by a "using" or "typedef" macro.

I am getting some compiler error messages which I am having a hard time to understand. Every error message is give in the code as comments.

Can you please help me understand what I am doing wrong in my code.

IDE: Visual Studio 15.7.3 (Language Standard: C++17. Other than that the default compiler options are used.)


#include <memory>
#include <vector>

template <class T>
class TreeContainer
{
    public:
        using pT = T *;
        using ContainerType = std::vector<pT>;
       
        // ...
       
        bool DeleteChild(T * const pChild);
        ContainerType & GetChildren1();
        ContainerType & GetChildren2();
       
        // ...
       
    private:
        ContainerType Children;
};

// ...

template <class T>
bool TreeContainer<T>::DeleteChild(T * const pChild)
{
    for (std::vector<T*>::iterator it=Children.begin(); it!=Children.end(); ++it)    // Error    C2760    syntax error: unexpected token 'identifier', expected ';'
    {
        if (pChild == (*it)[i])
        {
            delete *it;
            Children.erase(cit);
            return true;
        }
    }
    return false;
}

template <class T>
TreeContainer<T>::ContainerType & TreeContainer<T>::GetChildren1()    // ERROR: Error    C2061    syntax error: identifier 'ContainerType'
{    // ERROR1: Error    C2447    '{': missing function header (old-style formal list?),    ERROR2: Error    C2143    syntax error: missing ';' before '{'
    return Children;
}

// THIS WORKS
template <class T>
std::vector<T*> & TreeContainer<T>::GetChildren2()
{
    return Children;
}

// ...

TreeContainer.h

This type of error is almost always due to a missing typename.  In any context where the compiler isn't sure if something is a type or a variable, you need to write typename before the name of the type.

Try this:


for (typename std::vector<T*>::iterator it=Children.begin(); it!=Children.end(); ++it)

template <class T>
typename TreeContainer<T>::ContainerType & TreeContainer<T>::GetChildren1()

 

Advertisement

You were right. Adding "typename" solved everything. Actually I knew this rule, but I couldn't guess that it was the cause of the errors at this time.

Many thanks.

This topic is closed to new replies.

Advertisement