Reputation: 179
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
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