Conversion Issue

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 message? I provided a conversion operator, so everything should be fine.

+3
source share
1 answer

begin()cannot return the link to Iterator; it should return value Iteratorby value.

When a user-declared conversion to is called Iterator, it gives a temporary object Iterator. A link other than const cannot be bound to a temporary one, so the error you get when the begin()link returns.

However, the conversion function that returns Iteratoris unusual at best.

+3
source

Source: https://habr.com/ru/post/1759661/


All Articles