Considering a class, Foo, I want to define an operator[] overload that is actually a template, where the return type is templated:
class Foo
{
template<typename T> T operator[](size_t i)
{
return *(reinterpret_cast<T *>(get some pointer));
}
}
This works and compiles, but I can't figure out how to use it. I don't know where to specify the type when invoking it. To provide a reference example, suppose I replace operator[] with the function name at:
class Foo
{
template<typename T> T at(size_t i)
{
return *(reinterpret_cast<T *>(get some pointer));
}
}
Then I can do something like:
Foo foo;
int myFooInt = foo.at<int>(32); // gets an int at position 32
This compiles and given an actual implementation of some kind of positioned memory provided by "get some pointer", it returns the correct value. (Note, I'm not providing any information about what "position" means, and it really doesn't matter to my question, in this case.)
But I can't figure out how/where to specify the type when using [].
By the way, the following does work:
int myFooInt = foo.operator[]<int>(32);
but something like this doesn't compile:
int myFooInt = foo[32]<int>;
nor does this:
int myFooInt = foo<int>[32];
Is what I'm trying to do even possible?
It is not possible to provide explicit template arguments for operator syntax, your foo.at(ndx) is the usual answer if you want that sort of thing.
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