0

I have implemented getByte():

unsigned char& operator[](size_t i)
{
...
}

Now I would like to implement the counterpart getDword() that benefits from the already written char& operator:

unsigned int& operator[](size_t i)
{
...
/// call here operator for char& []
...
}

How can I achieve that with C++?

I'd like to do something like:

char c = x[100]; takes 1 char 
int d = x[100]: takes 4 char from 100 to 103

I have seen that you can overload operators by return type (const and non const operator). Its about some magic with *this

S.S
  • 1
  • 3
  • 9
    You cannot have a function signature that differs only by return type. https://stackoverflow.com/questions/9568852/overloading-by-return-type – Cory Kramer Nov 18 '16 at 12:35
  • call to opearator [] would be ambigous. – Samer Tufail Nov 18 '16 at 12:36
  • What is your "getByte" doing? What is your "getDword" supposed to do? – Some programmer dude Nov 18 '16 at 12:36
  • 2
    Just to be clear: "I have implemented getByte():" No - you've implemented operator[] ... – UKMonkey Nov 18 '16 at 12:36
  • As everyone already said, you cannot overload by return type. But you can make operator [] a template. Create an enum, which has 2 types: Byte,Dword, declare template [] function and create 2 specializations, one for Byte, second for Dword. – foxfireee Nov 18 '16 at 12:45
  • I have seen that you can overload operators by return type (const and non const operator). I cannot understand why this linus torvalds does not implemenmtt it in c++11! We are in XIX century for god. – S.S Nov 18 '16 at 12:47
  • 1
    @S.S It was **never** possible to overload methods by return type. If the return value is not used by caller, how do you deduce which one to call? You can, however, overload methods by their `const`-ness, because then, you can unambiguously deduce which one to call: if the object, on which method was called, is `const` - call `const` method; otherwise - call non-`const` method. – Algirdas Preidžius Nov 18 '16 at 13:06
  • If the return value is not used by caller, how do you deduce which one to call?. then give a compiler error, that simple it is – S.S Nov 18 '16 at 13:10
  • @S.S you can't, so compile fails – apple apple Nov 18 '16 at 13:12

0 Answers0