我需要Iterator< isConst = false>轉換為Iterator<isConst = true>. 也就是說,我需要一個單獨的方法Iterator< true >(const Iterator< false > &)。
我的迭代器類:
template < typename T >
template < bool isConst >
class ForwardList< T >::Iterator
{
using value_type = std::conditional_t< isConst, const T, T >;
using difference_type = ptrdiff_t;
using pointer = std::conditional_t< isConst, const T *, T * >;
using reference = std::conditional_t< isConst, const T &, T & >;
using iterator_category = std::forward_iterator_tag;
friend class ForwardList< T >;
private:
explicit Iterator(node_t *nodePtr): nodePtr_(nodePtr) {}
public:
Iterator() = default;
Iterator(const Iterator &other) = default;
~Iterator() = default;
reference operator*() const;
pointer operator->() const;
Iterator &operator ();
Iterator operator (int) &;
bool operator==(const Iterator &other) const;
bool operator!=(const Iterator &other) const;
private:
node_t *nodePtr_;
};
我嘗試多載復制建構式并專門化模板。我知道如果你把 Iterator 拆分成兩個類是可以的,但是我不想重復這么多代碼。
uj5u.com熱心網友回復:
Iterator<false>您可以使用一個回傳 的轉換運算子,而不是使用一個接受 的建構式Iterator<true>。
operator Iterator<true>() const { return Iterator<true>(nodePtr_); }
您將需要friend class Iterator<false>;訪問您的私有建構式。
現場觀看
uj5u.com熱心網友回復:
您可以使迭代器建構式接受具有任意模板引數的迭代器,除非構造的迭代器是非 const 迭代器并且建構式引數是 const 迭代器:
template < typename T >
template < bool isConst >
class ForwardList< T >::Iterator
{
...
friend class ForwardList<T>::Iterator<!isConst>;
public:
Iterator() = default;
template<bool otherIsConst, std::enable_if_t<isConst || !otherIsConst, int> = 0>
Iterator(Iterator<otherIsConst> const& other)
: nodePtr_(other.nodePtr_)
{
}
~Iterator() = default;
...
private:
node_t* nodePtr_ {nullptr}; // note: crash more likely for dereferencing the default-constructed object
};
static_assert(std::is_constructible_v<ForwardList<int>::Iterator<true>, ForwardList<int>::Iterator<true> const&>, "expected constructor unavailable");
static_assert(std::is_constructible_v<ForwardList<int>::Iterator<true>, ForwardList<int>::Iterator<false> const&>, "expected constructor unavailable");
static_assert(std::is_constructible_v<ForwardList<int>::Iterator<false>, ForwardList<int>::Iterator<false>const&>, "expected constructor unavailable");
static_assert(!std::is_constructible_v<ForwardList<int>::Iterator<false>, ForwardList<int>::Iterator<true> const&>, "unexpected constructor available");
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/529537.html
