【发布时间】:2018-05-03 22:19:17
【问题描述】:
我尝试编写一个按索引遍历容器的迭代器。
It 和 const It 都允许更改容器的内容。
Const_it 和 const Const_it 都禁止更改容器的内容。
之后,我尝试在容器上写一个span<T>。
对于不是 const 的类型 T,const span<T> 和 span<T> 都允许更改容器的内容。
const span<const T> 和 span<const T> 都禁止更改容器的内容。
代码无法编译,因为:
// *this is const within a const method
// But It<self_type> requires a non-const *this here.
// So the code does not compile
It<self_type> begin() const { return It<self_type>(*this, 0); }
如果我让It 的构造函数接受const 容器,它看起来不正确,因为迭代器可以修改容器的内容。
如果我去掉方法的 const,那么对于非 const 类型 T,const span<T> 不能修改容器。
It 继承自 Const_it 以允许在模板实例化期间从 It 隐式转换为 Const_it。
我在迭代器 (const C* container_;) 中使用指针而不是引用来允许将一个迭代器分配给另一个迭代器。
我怀疑这里有些不对劲,因为我什至想到:
Does cast away const of *this cause undefined behavior?
但我不知道如何解决。
测试:
#include <vector>
#include <numeric>
#include <iostream>
template<typename C>
class Const_it {
typedef Const_it<C> self_type;
public:
Const_it(const C& container, const int ix)
: container_(&container), ix_(ix) {}
self_type& operator++() {
++ix_;
return *this;
}
const int& operator*() const {
return ref_a()[ix_];
}
bool operator!=(const self_type& rhs) const {
return ix_ != rhs.ix_;
}
protected:
const C& ref_a() const { return *container_; }
const C* container_;
int ix_;
};
template<typename C>
class It : public Const_it<C> {
typedef Const_it<C> Base;
typedef It<C> self_type;
public:
//It(const C& container.
It(C& container, const int ix)
: Base::Const_it(container, ix) {}
self_type& operator++() {
++ix_;
return *this;
}
int& operator*() const {
return mutable_a()[ix_];
}
private:
C& mutable_a() const { return const_cast<C&>(ref_a()); }
using Base::ref_a;
using Base::container_;
using Base::ix_;
};
template <typename V>
class span {
typedef span<V> self_type;
public:
explicit span(V& v) : v_(v) {}
It<self_type> begin() { return It<self_type>(*this, 0); }
// *this is const within a const method
// But It<self_type> requires a non-const *this here.
// So the code does not compile
It<self_type> begin() const { return It<self_type>(*this, 0); }
It<self_type> end() { return It<self_type>(*this, v_.size()); }
It<self_type> end() const { return It<self_type>(*this, v_.size()); }
int& operator[](const int ix) {return v_[ix];}
const int& operator[](const int ix) const {return v_[ix];}
private:
V& v_;
};
int main() {
typedef std::vector<int> V;
V v(10);
std::iota(v.begin(), v.end(), 0);
std::cout << v.size() << "\n";
const span<V> s(v);
for (auto&& x : s) {
x = 4;
std::cout << x << "\n";
}
}
【问题讨论】:
-
您是要避免未定义的行为,还是要求用户在以未定义的行为方式使用
It时要注意? -
如果要编译,可以使用const_cast。例如:
It<self_type> begin() const { return It<self_type>(*const_cast<span*>(this), 0); } -
当用户使用
span<T>和const span<T>可能是 const 的类型 T 时,我想避免未定义的行为。