non-standard array access

Hi,
I am working on a problem with a constraint for accessing arrays. I cannot use the following common methods.

array[i]
*(array + i)

I've been looking around the forums and have only found a technique using &, but looked iffy. Any ideas?

-T
you can write it like so: i[array]
@coder7777 why does that work and what does the standard say? I've always thought that that was some weird compiler extension - why does that form exist?
Well, that would be considered the same format. A more accurate representation of the restrictions would be...

x[y]

and

*(x + y)

Thanks,
-T
There are many many ways to avoid using those exact forms - how broad are the limitations? Can you do this?
1
2
3
4
5
6
template<typename T>
T &Access(T *p, unsigned index)
{
    p += index;
    return *p;
}
@LB

Look at this:

http://en.wikipedia.org/wiki/Pointer_%28computer_programming%29

Subscript operator is commutative

@LB

I think the template is the way. This should be fun.

Thanks,
-T
@coder777
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
 
struct MyType
{
    operator size_t(){return 0;}
    MyType &operator[](size_t){return*this;}
};
 
int main()
{
    int a[] = {1, 2}, b = 0;
    MyType mt;
    std::cout << mt[a] << std::endl; //works
    std::cout << b[mt] << std::endl; //doesn't work
    std::cout << mt[mt] << std::endl; //works (looks ambiguous)
}
http://ideone.com/BVAPNr
I can understand why the third works, but why doesn't the second work?
Last edited on
LB wrote:
I can understand why the third works, but why doesn't the second work?
The difference is that the second cout the [] would result in a function call hence it's not a subscription.

std::cout << mt[mt] << std::endl; //works (looks ambiguous)
It's not ambiguous due to the operator size_t()
Topic archived. No new replies allowed.