Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ template return type of operator[]

Tags:

c++

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?

like image 554
Daniel Engel Avatar asked Dec 26 '17 00:12

Daniel Engel


1 Answers

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.

like image 60
SoronelHaetir Avatar answered Oct 15 '22 06:10

SoronelHaetir