1

While
var->atr
is a shortcut for
(*var).atr

Is there a shortcut for
(*var)->atr
which is the same as
(*(*var)).atr
(**var).atr

Perhaps something like a longer arrow?
var-->.atr

user3015682
  • 1,215
  • 12
  • 13
  • 1
    No, there is not. – Igor Tandetnik Apr 19 '20 at 03:01
  • `var[0]->atr`? I think `(*var)->atr` is the better looking one. But it's just a style thing. – JohnFilleau Apr 19 '20 at 03:02
  • 1
    For your "longer arrow" idea, see [What is the “-->” operator in C++?](https://stackoverflow.com/questions/1642028/what-is-the-operator-in-c). For your double de-reference issue, I'd advise seeking ways around needing it, which might make your code easier to read as a side-benefit. – JaMiT Apr 19 '20 at 03:18
  • Maybe, `#define dr(pp) (*(pp))->`... and use it like: `dr(var)atr` ? – Ghazi Apr 19 '20 at 03:40
  • As a historical note, this shows the mistake of having made the `*` dereference operator a prefix operator. If it had been a suffix operator, (a) we wouldn't need the `->` operator at all, and (b) you would have been able to write `var**.atr`. Of course a different symbol would have had to be used, as in Pascal's `^`, which in turn is enabled by it having the `xor` keyword. – user207421 Apr 19 '20 at 04:12
  • Ya, I guess `*` as a post-fix was reserved for multiplication, it's unfortunate they were unable to come up with another symbol to use. I suppose the `.` operator has precedence over dereference, hence requiring parenthesis `(*var).atr`. `var*.atr` and `var**.atr` would make it so easy to read and understand. – user3015682 Apr 19 '20 at 04:55

1 Answers1

1

No, there is no shortcut for two levels of indirection. We have to do either (**var).atr, or (*var)->atr.

If you really have a lot of levels of indirection, you may use a function template:

template <std::size_t N, typename T>
constexpr decltype(auto) deref(T&& t)
{
    if constexpr (N == 0) {
        return std::forward<T>(t);
    } else {
        return *deref<N - 1>(std::forward<T>(t));
    }
}

so that deref<10>(x).member means (**********x).member. I won't recommend this though.

L. F.
  • 19,445
  • 8
  • 48
  • 82
  • Thanks, didn't realize you could do `(**var).atr` , `(*(*var)).atr` is messy. I had no plans to use more than 2 levels of indirection, but that function template does look interesting! – user3015682 Apr 19 '20 at 05:07