views:

51

answers:

1

I have a class:

      template<class T>
        class MyClass
        {
        public:
                class Iterator {
    public:
    Iterator(MyClass<T>&){/*some code*/};
    };


  operator Iterator();
    Iterator& begin();
        };

    template<class T>
    MyClass<T>::operator typename MyClass<T>::Iterator()
    {
        return MyClass::Iterator(*this);
    }

    template<class T>
    typename MyClass<T>::Iterator& MyClass<T>::begin()
    {
        return *this;//<---------------cannot convert from MyClass to MyClass<T>::Iterator
    }

Why am I getting an error? I've provided conversion operator so everything should be fine.

+3  A: 

begin() cannot return a reference to an Iterator; it needs to return an Iterator by value.

When the user-declared conversion to Iterator is called, it yields a temporary Iterator object. A non-const reference cannot be bound to a temporary, hence the error you get when begin() returns a reference.

That said, having a conversion function that returns an Iterator is unusual at best.

James McNellis
@James my bad I just didn't put it into example. Fix it in a sec.
smallB