I am trying to implement a custom container and I need to make an iterator for it. I want to squish const iterator and non-const iterator in one class definition. and here is the issue I have encountered:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include<type_traits>
template <typename T, bool is_const = true>
class node_itr
{
public:
typedeftypename std::conditional<is_const, node<T>*, node<T>* >::type node_T_ptr;
node_itr(node_T_ptr d = 0):data(d){}
node_itr(node_itr<T,true>& n):data(n.data){}
//Question: I have to use reference here for converting a non-const iterator to a const iterator,
//but I cannot do such conversion on rvalues of non-const, such as vec.begin().
// ...other utilities are omitted
private:
node_T_ptr data;
}
I cannot convert a rvalue of non-const node_itr to a const node_itr object, because the compiler requires to use reference& in the copy constructor for this case to avoid recursive conversion! (note: I chose to use a bool parameter in the template so that we only need to change the type of pointer we need for non-const and const iterators.)
Note:
I've read that one can use std::iterator and can go down this path: