Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphic operator [] implementation

Tags:

c++

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 [].

like image 611
berkus Avatar asked Oct 10 '10 15:10

berkus


1 Answers

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.

like image 194
Johannes Schaub - litb Avatar answered Oct 24 '22 00:10

Johannes Schaub - litb