Polymorphic operator []

Suppose 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 compiled idiomatic C ++?

It should look like

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

those. polymorphic operator [].

+6
c ++
source share
1 answer

What you can do is return the 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 something similar.

+7
source share

All Articles