设计一个惰性向量:const的问题 [英] Designing a lazy vector: problem with const

查看:115
本文介绍了设计一个惰性向量:const的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个小的延迟向量类(或延迟向量),它应该看起来像一个 std :: vector c> std :: vector ,但是它加载它的元素lazily,即它将加载元素 n )从磁盘每当有人访问元素 n 。 (原因是在我的应用程序中,并非所有元素都适合内存。)

I wrote a little "lazy vector" class (or, delayed vector) which is supposed to look like a std::vector and usable wherever a std::vector is used, but it loads its elements "lazily", i.e. it will load element n (and possibly a few more) from disk whenever someone accesses element n. (The reason is that in my app, not all elements fit into memory.)

这是 LazyVector ,但是使用这样的向量的 const 成员函数有一个问题,见下文。

Here is this LazyVector class, but there is a problem with const member functions that use such a vector, see below.

template<class T>
class LazyVector {
  std::vector<T> elems_;
  void fetchElem(unsigned n){
    // load the n-th elem from disk into elems_ etc
  }
public:
  const T& operator[](unsigned n) const {
    fetchElem(n); // ERROR: ... discards qualifiers       
    return elems_[n];
  }
  T& operator[](unsigned n) {
    fetchElem(n);
    return elems_[n];
  }
  // and provide some other std::vector functions
};

正如我所说,有一个问题,当 const 成员函数请求 LazyVector 的元素。由于 LazyVector 的性质,访问一个元素是不是 const 下面的向量 vec ,在此上下文中禁止。成员函数 foo 必须为 const ,且不能更改。如何解决这个问题?

As I said, there is a problem when a const member function asks for an element of the LazyVector. By nature of the LazyVector, accessing an element is not const, i.e. it will change the vector vec below, which is forbidden in this context. The foo member function must be const and cannot be changed. How can I solve this?

class Foo {
  LazyVector<const std::string*> vec;
  void fct(int n) const { // fct must be const 
    const std::string* str = vec[n];
    // do something with str 
  }
};


推荐答案

可以使用可变成员数据或const_cast实现你的LazyVector类。因此,你可以创建消费类所需的constness的幻觉,而不是const。

You can either use mutable member data or const_cast in the implementation of your LazyVector class. Thus you can create the illusion of constness needed by your consuming class without actually being const.

这篇关于设计一个惰性向量:const的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆