evo8198
evo8198

Reputation: 179

Can a member operator be used without referring to the "this" pointer?

I would like to overload the [] operator and use it within a member function without referring to the this pointer, because the point of overloading, at least in this case, is brevity. I don't think it can be done, can it? It seems inconsistent that I can access member functions without dereferencing this, but not member operators.

#include <iostream>

struct demo {
  int i;

  void operator [](demo d) {
    std::cout << "operator called [" << d.i << "]" << std::endl;
  }

  void run() {

    demo k = { 5 };

    (*this)[k] ;          // works
    this->operator[](k);  // works
    // [k]                // fails - why?    
  }

};

Upvotes: 1

Views: 74

Answers (2)

Quimby
Quimby

Reputation: 19113

Just writing [k]; is simply syntactically incorrect in C++. Why? Maybe because no one though to make it a feature, it is pretty niche and not really readable.

In post-C++11 it is most likely parsed as a lambda with missing body, that is why a compiler complains about expected {. For example [k]{return k;}; is a correct lambda definition.

Upvotes: 3

MikeCAT
MikeCAT

Reputation: 75062

You can use it without this like

operator[](k);

Upvotes: 9

Related Questions