Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with conversion

Tags:

c++

templates

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.

like image 666
smallB Avatar asked Aug 02 '26 18:08

smallB


1 Answers

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.

like image 145
James McNellis Avatar answered Aug 05 '26 08:08

James McNellis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!