除了一个只读条目外,其他所有条目都为只读的向量的实现
implementation of a vector with all but one read only entries
我想基本上实现一个向量,它只允许写入在构建时传递给它的一个条目。类似这样的东西:
// 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
访问向量以读取任何其他元素。如果只传入编译时积分常量作为参数,则模板参数将不起作用。
相关文章:
- 如果没有malloc,链表实现将失败
- 如何在c++中实现处理器调度模拟器
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 使用简单类型列表实现的指数编译时间.为什么
- 如何在BST的这个简单递归实现中消除警告
- 实现一个在集合上迭代的模板函数
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 如何正确实现和访问运算符的各种自定义枚举器
- C++Union/Struct位域的实现和可移植性
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 在c++中实现LinkedList时,应出现未处理的错误
- 为左值和右值的包装器实现C++范围
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- 使用GSoap实现ONVIF
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 非常量变量只读位置的赋值
- 用于AVX的ln(x)的实现,m256
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 除了一个只读条目外,其他所有条目都为只读的向量的实现