0

I'm trying to overload operator[] using a template so it is possible to choose what type is returned. Simplified example:

class A
{
    uint8_t buff[10];

public:
    template<typename T> 
    T operator[] (uint var)
    {
        return (T)buff[var]; 
    }
};

Now I want to be able to do something like this:

abc<uint16_t>[5]; // Clearly not allowed

abc.operator[]<uint16_t>(5); // This works but it's stupid

Question: Is it possible to overload operator [] this way? If not, what is the correct way to achieve it?

Pari
  • 458
  • 2
  • 6
  • 15
  • You wont be able to use it this way : `abc[5]`. Give a look to : https://stackoverflow.com/questions/35853204/c-overloading-operator-in-a-template-class – Adrien Givry Aug 22 '19 at 12:42
  • 1
    As the duplicate indicates, you need to write out `operator[]` unless you can implicitly deduce the template argument. You can't in this case. Maybe an `at(5);` or something would suit your needs better. – François Andrieux Aug 22 '19 at 12:44
  • @AdrienGivry The link was not present at the time of my comment. But the first portion of the comment is still redundant. – François Andrieux Aug 22 '19 at 12:45
  • 1
    Such implicit casting is often a bad idea. And C-style casting is really a red flag of you doing something wrong. Return the actual type and have the caller do the conversion if needed. – Some programmer dude Aug 22 '19 at 12:46
  • 1
    But if you use the template parameter just for the cast, why not use the cast outside the function, eliminating the need of templates? – Petok Lorand Aug 22 '19 at 12:46
  • @Someprogrammerdude this is just a very simplified example created to show the idea of syntax I'd like to achieve – Pari Aug 22 '19 at 12:50
  • 3
    Depending on use-case, requirements and design, it might be a better idea to have an explicit "convert to this type" function, as in `template T as(unsigned index) { return reinterpret_cast(buff[index]); }` Another way which is usually nicer is to have the `operator[]` function return a *proxy object* with such an `as` function. Then you could do e.g. `abc[5].as()`. – Some programmer dude Aug 22 '19 at 12:52
  • @Someprogrammerdude Thanks, I think this is exactly what I'm looking for here – Pari Aug 22 '19 at 12:54
  • Or you can write a small macro : `#define ELEMENT(Value) operator[](Value)` and use it like `auto result = foo.ELEMENT(5u);`. This way, you'll be able to call any templated `operator[]` without writing too much – Adrien Givry Aug 22 '19 at 12:57
  • 2
    @AdrienGivry Each time a macro like this is being written, a kitten dies. – Guillaume Racicot Aug 22 '19 at 13:18

0 Answers0