c++templatesoperator-keywordnon-member-functions

Non member comparison operator for a template class


I have defined a template container Tree<T>, with two member-class iterators : const_iterator and iterator

Now I would like to add non member comparison operators:

template<typename T>
bool operator==(Tree<T>::const_iterator a, Tree<T>::iterator b)
{
    return a.ptr() == b.ptr();
}

But I have the compilation error:

declaration of 'operator==' as non-function

Why? Is this due to the template?


Solution

  • You need to use typename for the dependent name here, e.g.

    template<typename T>
    bool operator==(typename Tree<T>::const_iterator a, typename Tree<T>::iterator b)
    //              ~~~~~~~~                            ~~~~~~~~
    {
        return a.ptr() == b.ptr();
    }