【发布时间】: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<bool>,如果您修改不可写索引的值,则会抛出该对象。 -
你可能认为你想这样做,但你不想这样做。一个允许您为您喜欢的任何索引调用 setter 的接口,除非您使用在构造时传递给它的特殊索引,否则它会生成错误,除非它也通过另一个传递给您,否则您无法知道频道……太疯狂了。
-
我不清楚如何使用模板或代理对象来做到这一点。你能回答如何使用这些实现吗?用例是有多个节点,每个节点拥有一个表的一行。允许节点修改自己的行,但可以通过 RDMA 读取其他行。我只是想有一个像这样干净的表示。它不会导致任何混乱,因为可写入节点的行就是它拥有的行。
标签: c++ class vector operator-overloading