For a built in type integer array say
int a[10];
int i = 2;
a[i] = 10;
alternatively
i[a] = 10;
because
a[i] is a postfix expression that is *(a+i) or *(i+a) because commutative property of addition.
I want to achieve that for a userdefined type say
class Dummy
{
//
};
Is it possible?
If yes then how?
If no then why?
EDIT :-
I know it is ugly but following code compiles :-
g++ -dumpversion
4.3.3
#include <stdio.h>
#include<iostream>
#include <string.h>
#include <malloc.h>
using namespace std;
int main()
{
string ArrayS[10];
2[ArrayS] = "ADASD" ;
cout << 2[ArrayS] << endl;
return 0;
}
It is impossible because "
operator[]shall be a non-static member function with exactly one parameter" (standard §13.5.5/1), so you cannot define it such that the first argument is of native scalar type.(Furthermore, a nonstatic operator overload call is interpreted as a member call, so the first operand cannot be implicitly converted, unlike a free function overload. This is one reason why free function overloads are preferred when possible.)
For better or worse,
index[ object ]is a way to ensure that nooperator[]overload gets called.However.
"The expression
E1[E2]is identical (by definition) to*((E1)+(E2))" (§5.2.1) andoperator+can be overloaded so long as one side is not native type. This leaves twooptionsvulnerabilities: the "array" must be a class, or the "index" must be a class orenum.You would then have to define a proxy type to hold the result of "addition," which defines an
operator*overload. GCC does not support this, however. I’ll look deeper into other platforms and references.Edit: Ah, §13.6/13 overrides 5.2.1 and declares that, for the sake of interpreting an expression involving class or enumeration type, there are functions
T& operator[](std::ptrdiff_t, T*);andT& operator[](T*, std::ptrdiff_t);. So that’s that.