【问题标题】:implementation of a vector with all but one read only entries一个向量的实现,除了一个只读条目
【发布时间】:2015-11-21 02:03:02
【问题描述】:

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

// 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 函数等建议。

【问题讨论】:

  • my_index 可以作为模板参数吗?如果是这样,我认为这会更容易一些。编辑:另外,如果您希望错误“最好在编译时”出现,那么这是必要的。如果您对为什么想要这种数据结构给出一些动机,它也可能对这个问题有所帮助,它听起来并不是特别有用。
  • 除了模板选项之外,我能想到的唯一其他方法是返回一个代理对象,例如 vector&lt;bool&gt;,如果您修改不可写索引的值,则会抛出该对象。
  • 你可能认为你想这样做,但你不想这样做。一个允许您为您喜欢的任何索引调用 setter 的接口,除非您使用在构造时传递给它的特殊索引,否则它会生成错误,除非它也通过另一个传递给您,否则您无法知道频道……太疯狂了。
  • 我不清楚如何使用模板或代理对象来做到这一点。你能回答如何使用这些实现吗?用例是有多个节点,每个节点拥有一个表的一行。允许节点修改自己的行,但可以通过 RDMA 读取其他行。我只是想有一个像这样干净的表示。它不会导致任何混乱,因为可写入节点的行就是它拥有的行。

标签: c++ class vector operator-overloading


【解决方案1】:

要么为访问器和修改器命名不同的东西,例如v[i]v.set(x),要么让非常量operator[] 返回end(),而不是幻数,并使客户端通过@ 访问向量987654325@ 或 const_cast 阅读任何其他元素。如果您将编译时整数常量以外的任何内容作为参数传递,则模板参数将不起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-12
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    • 2021-09-24
    • 2018-12-05
    • 1970-01-01
    相关资源
    最近更新 更多