tags:

views:

406

answers:

6

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;
}
+15  A: 

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 no operator[] overload gets called.


However.

"The expression E1[E2] is identical (by definition) to *((E1)+(E2))" (§5.2.1) and operator+ can be overloaded so long as one side is not native type. This leaves two options vulnerabilities: the "array" must be a class, or the "index" must be a class or enum.

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*); and T& operator[](T*, std::ptrdiff_t);. So that's that.

Potatoswatter
Even if you do find an obscure way to do it. Please don't tell anybody as we will spend all next year trying to explain to C++ newbies why it is a bad idea. :-)
Martin York
Could `index[ object ]` ever invoke an implicit conversion from `object` to some pointer type?
Ben Voigt
@Ben: Yes: `struct foo { operator const foo*() const { return this; } }; int main() { foo f; 5[f]; // UB }`. I can't see any way to utilize it, because once you've converted to a pointer you're in non-user-defined behavior territory. (And anything but `0[f]` leads to UB, unless `f` is in an array.)
GMan
Thanks for checking that. I think I see a way. I'll work up an example.
Ben Voigt
@Ben: I'm extremely confident it's impossible. I posted an answer why.
GMan
@Ben: Race you!
Potatoswatter
I win the race? Anyway, that definition only holds when one of the operands has pointer type. <quote> A postfix expression followed by an expression in square brackets is a postfix expression. One of the expres-sions shall have the type “pointer to T” and the other shall have unscoped enumeration or integral type.</quote> The workaround is... ugly?
Ben Voigt
@Ben: You win! Nice! I was foiled by the fact that the enumerated type is promoted to `ptrdiff_t` before the addition.
Potatoswatter
A: 
andand
Can you elaborate on that?
Dummy00001
I'm not sure I understand how this gets the desired behavior. `dummy d; 5[d];` won't wok.
GMan
@GMan: The OP was a little vague on exactly how the user defined type was to be used, so I took the liberty of assuming that the intent was that both the index and the thing being indexed were of the same user defined type. Perhaps that was a bad assumption...?
andand
A: 

Any Dummy that was declared and used as an array will work the same way, if Dummy can be implicitly cast to an integer.

Scott Stafford
+2  A: 

a[i] = 10;
i[a] = 10;
because a[i] is a postfix expression that is *(a+i) or *(i+a) because commutative property of addition.

Yes. But a[i] == i[a] == *(a+i) == *(i+a) is because the notation a[i] in C is a syntactic sugar for the latter pointer arithmetic. Keyword here "in C". C++ in large tries to part ways from the pointer arithmetic. Thus the a[i] as a syntactic sugar is only supported on the POD for backward compatibility with the C. But that does not work on any C++ objects since the operations [] has clear semantic specified and it doesn't allow the C-like syntax tricks.

In the end, do not do it. The trick is an obscure remnant of the older times and doesn't have a single good reason to be reincarnated.

Dummy00001
`i[a]` works on any pointer type, not just pointer to POD.
Potatoswatter
@Potatoswatter: pointer is a POD, what it points to - may be not. Unfortunately POD is the only nomenclature I know for differentiating C++ objects from C objects.
Dummy00001
Okay, okay. Not every pointer is POD. But most are.
Dummy00001
@Dummy: All pointers are POD. But POD classes may have operator overloads, too.
Potatoswatter
@Potatoswatter: I'm lazy to test the edge case, but the pointer to virtual method isn't a standard pointer and is not compatible with `void *`. Compiler make it look like one, but it's not: careless conversions to `void *` may destroy the virtual-ness property.
Dummy00001
@Dummy: pointers to members aren't pointers. 5.2.1 doesn't apply to them.
Potatoswatter
@Potatoswatter: As per 3.9.2, pointer to non-static member is a compound type. Compound types are POD. But in the same 3.9.2 *text referring to “pointers” does not apply to pointers to members.* Go figure.
Dummy00001
But I hope we all can agree that the practice of `i[a]` isn't something worth resurrection.
Dummy00001
+2  A: 

It is completely impossible to do. Potatoswatter correctly points out you couldn't possibly define any operator such as operator[](int, T), so overloading for an integer on the left is impossible.

But consider that this works:

struct foo
{
    operator const foo*() const
    {
        return this;
    }
};

int main()
{
    foo f;
    5[f]; // UB
}

Is there a way to utilize this? No:

5.2.1 Subscripting
A postfix expression followed by an expression in square brackets is a postfix expression. One of the expressions shall have the type “pointer to T” and the other shall have enumeration or integral type. The result is an lvalue of type “T.” The type “T” shall be a completely-defined object type.56) The expression E1[E2] is identical (by definition) to *((E1)+(E2)).

With E1 being an integral type, E2 must be a pointer type. So we can't inject user-behavior there.

The only thing left is + and *. We can't change operator+ for an integral type and a pointer, because that's defined by the language. The result of E1 + E2 is going to be a pointer, and we can't define operator* for a pointer either.

Therefore, injecting user-defined behavior is impossible.

GMan
Why must `E2` be a pointer type?
Potatoswatter
@Potato: "One of the expressions shall have the type “pointer to T” and the other shall have enumeration or integral type." One must be a pointer, the other must be an integer. If `E1` is an integer, then...
GMan
Ah, lol. Mostly I focused on the enumeration hack, which would be more interesting anyway.
Potatoswatter
+2  A: 

With C++, nothing is impossible. It is however, a terrible terrible idea. Don't do this.

#include <memory>
#include <stdlib.h>
#include <stdio.h>

void *aligned_malloc( size_t bytes, size_t alignment ) {
    void *p = malloc( bytes + alignment ), *pa = reinterpret_cast<void*>( reinterpret_cast<size_t>(p) + alignment &- alignment );
    reinterpret_cast<void**>(pa)[-1] = p;
    return pa;
}

void aligned_free( void *pa ) {
    void *p = reinterpret_cast<void**>(pa)[-1];
    free( p );
}

struct SupportReverseIndexer
{
    class IndexerReversal
    {
        static const size_t alignment;
        friend struct SupportReverseIndexer;
        friend class std::auto_ptr<IndexerReversal>;
        struct SupportReverseIndexer* const m_parent;
        IndexerReversal(struct SupportReverseIndexer* parent) : m_parent(parent) {}
        void* operator new(size_t bytes) { return aligned_malloc(bytes, alignment); }
        void operator delete(void* p) { aligned_free(p); }
        static struct SupportReverseIndexer* getParent(IndexerReversal* pThis)
        {
            size_t iThis = reinterpret_cast<size_t>(pThis);
            iThis += alignment >> 1;
            iThis &= ~(alignment  - 1);
            return reinterpret_cast<IndexerReversal*>(iThis)->m_parent;
        }
    public:
        operator size_t() { struct SupportReverseIndexer* const parent = getParent(this); return parent->indexer(this-parent->ir.get()); }
    };

    SupportReverseIndexer() : ir(new IndexerReversal(this)) {}

    operator IndexerReversal*() { return ir.get(); }

private:
    std::auto_ptr<IndexerReversal> ir;
    size_t indexer(size_t index) { printf("Custom operator[] called, index = %i\n", index); return index; }
};

const size_t SupportReverseIndexer::IndexerReversal::alignment = 0x10000 * sizeof(SupportReverseIndexer::IndexerReversal);

int main(void)
{
    SupportReverseIndexer sri;
    int a = sri[2];
    a = 3[sri];
    a = (-5)[sri];

    return 0;
}

No, really, DON'T DO THIS!!!!!

Ben Voigt
OK, I see. The index must be less than the alignment of the proxy object. The spare bits are used to recover the argument. The proxy must be convertible to the result type.
Potatoswatter
Thanks for the portable aligned_malloc implementation. I just added space for the (original address) field to the size passed to malloc.
Ben Voigt
Sorry about the reinterpret_casts… you don't need to add `sizeof(void*)` because it's already included in the padding. `malloc` is guaranteed to align to `sizeof(void*)` already, so we guarantee to add at least that much at the beginning. When you add to the argument of malloc, that padding goes onto the end instead.
Potatoswatter
Oh now I see... I was worried about the case where the malloc result was already aligned but you still move forward to the next aligned address so there's always space for the original address.
Ben Voigt
Please also note that I'm fairly sure that UB is achieved as soon as the pointer addition is done, even though the invalid pointer is never actually dereferenced.
Ben Voigt
@Ben: It might not be as bad as it looks. If `IndexerReversal` is made POD (which looks possible), the `malloc` legitimately allocates an array of them. Then it's a matter of not using uninitialized data and not forming a pointer outside the allocated range. There should be equal padding before and after the valid element, if negative offsets are allowed. However, the pointer-as-integer arithmetic is probably UB, since the mapping of pointers to integers can rearrange the bits or whatever.
Potatoswatter