tags:

views:

97

answers:

1

Lets say we have this code:

class test_t
{
    void* data;
public:
    template <typename T>
    T operator [](int index)
    {
        return reinterpret_cast<T*>(data)[index];
    }
};

int main()
{
    test_t test;
    int t = test.operator []<int>(5);
    return 0;
}

Is there a way to convert it to compilable idiomatic C++?

It should look like

int main()
{
    test_t test;
    int t = test[5];
    double f = test[7];
    return 0;
}

I.e. a polymorphic operator [].

+6  A: 

What you could do is to return a proxy object

struct Proxy {
    template<typename T>
    operator T() {
      return static_cast<T*>(data)[index];
    }
    void *data;
    int index
};

Proxy operator [](int index)
{
    Proxy p = { data, index };
    return p;
}

You can resort to obj.get<T>(index) or to something similar too.

Johannes Schaub - litb
Interesting solution. +1.
DeadMG
Yay, excellent. This really seems to work, I replaced the initializer style init to constructor for Proxy, and used reinterpret_cast<> but it does work! Thank you.
Berkus
To allow use of returned object as lvalue I just added the following operator to Proxy: `template<typename T>` `Proxy` `return *this;` `}`
Berkus
Oops. In the original code the data was treated as an array of T. In the above the user's index `i` selects the `sizeof(T)` bytes starting at the `i`'th byte of the data...
Alf P. Steinbach
@Alf ohh! Excellent. Lemme fix it
Johannes Schaub - litb
Actually, I need to treat index as byte offset into a buffer, so original version was fine.
Berkus