简体   繁体   中英

no suitable user-defined conversion, but the convertion is specified

I am coding a vector class with iterators for a school exercice. I am getting the following error and I don't know how to go about it:

'no suitable user-defined conversion from "vectorIterator" to "vectorIterator< const int>" exists'

This is the code I am trying to execute:

vector<int> v;
v.push_back(1);
v.push_back(2);
vector<int>::const_iterator it = v.begin();

This is part of the code in my class vector:

template <typename T, typename Alloc = std::allocator<T> >
class vector {
..
public:
typedef vectorIterator<value_type>          iterator; 
typedef vectorIterator<const value_type>    const_iterator;
..
iterator        begin()         { return iterator(m_data); } // if commented the above code works
const_iterator  begin() const   { return const_iterator(m_data); }
..
}

If I comment the first form of begin() the code compiles and runs ok, so it seems that it obscures the const form. I would expect the compiler to know to use the const form of begin(), but it does not. What am I missing?

Thanks a lot

Since vectorIterator is a template class, which means that vectorIterator<int> and vectorIterator<const int> are two different types, they can not be converted to each other. You need to add a conversion constructor for vectorIterator<const int> that accepts vectorIterator<int> , using template should be enough (some constraints on U are omitted here for simplicity):

template<typename T>
struct vectorIterator { 
  // ...
  template<typename U>
  vectorIterator(vectorIterator<U>);
};

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM