What is the point of this [i] in C ++ without overloading

This is the code from WebKit:

class ExecState : public Register { JSValue calleeAsValue() const { return this[JSStack::Callee].jsValue(); } ... } 

JSStack::Callee const , Operator[] does not overload in ExecState or Register ,

So what is the syntax in C ++ for this[JSStack::Callee] ?

+6
source share
1 answer

Well, this is a pointer to ExecState and using the index operator with a pointer makes it behave as if it were an array. That is, the expression this[JSStack::Callee] refers to the object that is in JSStack::Callee , from this . Of course, this can only work if the element is a member of an array of ExecState objects.

The following is a separate demonstration of the use of this "feature". In general, I would recommend not using it, but there can be very specific needs when it is known that the type is used in an array and access is viable. For example, if a type is defined locally, all known uses can be known (I would add a comment that states this assumption, though).

 #include <iostream> class foo { int d_value; public: foo(int i): d_value(i) {} int get(int i) const { return this[i].d_value; } }; template <typename T, int Size> int size(T(&)[Size]) { return Size; } int main() { foo f[] = { 9, 1, 8, 2, 7, 3, 6, 4, 5 }; for (int i=0; i < size(f) - 2; ++i) { std::cout << "f[" << i << "].get(2)=" << f[i].get(2) << '\n'; } } 
+5
source

Source: https://habr.com/ru/post/977239/


All Articles