除了一个只读条目外,其他所有条目都为只读的向量的实现

implementation of a vector with all but one read only entries

本文关键字:只读 实现 向量 其他 一个      更新时间:2023-10-16

我想基本上实现一个向量,它只允许写入在构建时传递给它的一个条目。类似这样的东西:

// create a vector v of size s where only v[my_index] is writable
myVector <T> v (s, my_index); 
// read of any index is allowed, so following succeeds for any index
std::cout << v [index] << std::endl;
// if index is not equal to my_index, following generates an error
// preferably at compile time
v [index] = t;

在这一点上,我认为这是不可能实现的。我在网上搜索了一下,可以找到以下myVector的实现,它以一种巧妙的方式使用常量引用,但不允许对任何元素进行写访问。

#include <vector>
using namespace std;
template <class T>
class myVector {
  int my_index;
  vector <T> _v;
public:
  const vector <T> &v;
  myVector (int size, int _my_index);
  const T* operator [] (int index);
};
template <class T>
myVector<T>::myVector (int size, int _my_index) : v(_v) {
  my_index = _my_index;
  _v.resize (size);
}
template <class T>
const T* myVector<T>::operator [] (int index) {
  return &v[index];
}

有办法做到这一点吗?这样做的全部动机是能够为向量提供一个良好的访问接口,因此不欢迎使用getter-setter函数等建议。

可以将accesor和mutator命名为不同的东西,例如v[i]v.set(x),或者让非常数operator[]为除幻数之外的任何数字返回end(),并让客户端通过const&const_cast访问向量以读取任何其他元素。如果只传入编译时积分常量作为参数,则模板参数将不起作用。