Feb 25, 2013 at 3:18pm UTC
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
Feb 25, 2013 at 3:29pm UTC
you can write it like so: i[array]
Feb 25, 2013 at 3:35pm UTC
@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?
Feb 25, 2013 at 3:37pm UTC
Well, that would be considered the same format. A more accurate representation of the restrictions would be...
x[y]
and
*(x + y)
Thanks,
-T
Feb 25, 2013 at 4:31pm UTC
@LB
I think the template is the way. This should be fun.
Thanks,
-T
Feb 25, 2013 at 5:04pm UTC
@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 Feb 25, 2013 at 5:05pm UTC