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 [].
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With