views:

96

answers:

2

Hi All,
This may be very obvious question, pardon me if so.

I have below code snippet out of my project,

#include <stdio.h>
class X
{
  public:
   int i;
   X() : i(0) {};
};

int main(int argc,char *arv[])
{
  X *ptr = new X[10];
  unsigned index = 5;
  cout<<ptr[index].i<<endl;
  return 0;
}

Question
Can I change the meaning of the ptr[index] ? Because I need to return the value of ptr[a[index]] where a is an array for subindexing. I do not want to modify existing source code. Any new function added which can change the behavior is needed.

Since the access to index operator is in too many places (536 to be precise) in my code, and has complex formulas inside the index subscript operator, I am not inclined to change the code in many locations.


PS :
1. I tried operator overload and came to conclusion that it is not possible.
2. Also p[i] will be transformed into *(p+i). I cannot redefine the basic operator '+'.

So just want to reconfirm my understanding and if there are any possible short-cuts to achieve.
Else I need fix it by royal method of changing every line of code :) .

+3  A: 

Yes, it is not possible to define custom operators where all of the arguments are of built-in types (this includes raw pointers).

Also it's almost always not a good idea to define operators in a non-obvious way like this.

You may want to consider swapping out a raw pointer to X with a class that behaves like one. It may be easier, depending on your code (e.g. if you have a lot of templates).

Alex B
Thanks! Alex, Nice suggestion.
kumar_m_kiran
+2  A: 

As Alex says, your 'subindexing' usage of [] would be totally nonobvious for anyone reading your code.

That said, you can define a class such as this:

template<class T>
class SubindexingList {
    vector<T> data;
    vector<int> subindexes;
public:
    SubindexingList(int count) : data(count) { }
    void set_subindexes(vector<T> const& newval) { subindexes = newval; }
    T& operator[](int index) { return data[subindexes[index]]; }
    T const& operator[](int index) const { return data[subindexes[index]]; }
};

And replace your X *ptr = new X[10]; with SubindexingList<X> stuff(10);.

Stefan Monov
You beat me to this solution - only thing is it would be nice to pass in subindexes to constructor and determine size from it. If possible. Used in the right context, this might not be as bizarre as it sounds...
Stephen
yes, of course, but the details didn't matter for this answer
Stefan Monov
@Stefan, Thanks! Buy far the best possible solution. Though I liked previous post which you provided (Where the sub indices was passed in constructor.., This would force something of the user).
kumar_m_kiran