Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessors without the (), or const references to a member variable

I am interested in creating a class I can use like

class MyClass {
  vector<int> m_vec;
public:
  // Either this
  const& vector<int> vec;
  // Or some version of this. 
  const& vector<int> getVec() { return m_vec } ;

  MyClass() : vec(m_vec) {}
  void changeVec() { m_vec.push_back(5); }
}

Now if I want to use getVec(), the syntax is a little cumbersome:

myClass.getVec()[5]

I would much prefer to be able to either somehow use

myClass.vec[5]

without exposing the ability to modify the vector. IE, I want the member variable to be private, but for a const-version of the variable to be public without a syntactical or performance overhead.

If I add the const& vector reference, the compiler (at least my version of GCC) actually makes the class take more memory. So

  1. How can I create an alias to a member variable without making it use more memory, or
  2. How do I avoid the parens in the myVec()[] accessor? Just defining myVec(int idx) is not a satisfactory option since I want to call multiple methods on it.

Just to be clear, this is an example -- in the real case, the usage is a bit more compelling than in the vector case. Also, the memory usage is important as lots of these objects exist and will be copied, so this is not premature optimization. At this point, I'm using the getVec()[0] approach, but the ugliness is killing me.

like image 231
bsdfish Avatar asked Dec 09 '22 10:12

bsdfish


1 Answers

If, for some reason, MyClass::operator[] is not suitable, just make a tiny wrapper class for your vector.

struct Wrapper {
  friend class MyClass;
  int operator[](size_t s) const { return vec[s]; }
private:
  vector<int> vec;
};

class MyClass {
public:
  Wrapper vec;
};
like image 112
Erik Avatar answered Apr 28 '23 08:04

Erik