Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using boost::shared_ptr with classes that overload the subscript operator ([])

I have a class that overloads the subscript operator:

class SomeClass
{
public:

   int& operator[] (const int idx)
   {
      return someArray[idx];
   }  

private:

   int someArray[10];
};

This of course allows me to access the array elements of the someArray member like so:

SomeClass c;
int x = c[0];

However, some instances of SomeClass will be wrapped in a boost shared pointer:

boost::shared_ptr<SomeClass> p(new SomeClass);

However, in order to use the subscript operator I have to use a more verbose syntax that kind of defeats the succinctness of the subscript operator overload:

int x = p->operator[](0);

Is there any way to access the subscript operator in a more shorthand manner for such instances?

like image 979
OhMyGodThereArePiesEverywhere Avatar asked Nov 16 '13 12:11

OhMyGodThereArePiesEverywhere


1 Answers

Both juanchopanzaand DyP have answered my question sufficiently. After googling regarding the etiquette for answers found in comments, it was suggested to post a self-answer referencing the correct answers in the comments in order to close the question (I have to wait 2 days to accept my own answer, though).

juanchopanza's answer is as follows:

int x = (*p)[0];

DyP's answer is as follows:

SomeClass& obj = *p;
int x = obj[0];

Thank you both for your contributions.

like image 67
OhMyGodThereArePiesEverywhere Avatar answered Oct 15 '22 09:10

OhMyGodThereArePiesEverywhere