Operator[][] overload

前端 未结 18 1857
轮回少年
轮回少年 2020-11-22 05:46

Is it possible to overload [] operator twice? To allow, something like this: function[3][3](like in a two dimensional array).

If it is pos

18条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 06:19

    It 'll be great if you can let me know what function, function[x] and function[x][y] are. But anyway let me consider it as an object declared somewhere like

    SomeClass function;
    

    (Because you said that it's operator overload, I think you won't be interested at array like SomeClass function[16][32];)

    So function is an instance of type SomeClass. Then look up declaration of SomeClass for the return type of operator[] overload, just like

    ReturnType operator[](ParamType);

    Then function[x] will have the type ReturnType. Again look up ReturnType for the operator[] overload. If there is such a method, you could then use the expression function[x][y].

    Note, unlike function(x, y), function[x][y] are 2 separate calls. So it's hard for compiler or runtime garantees the atomicity unless you use a lock in the context. A similar example is, libc says printf is atomic while successively calls to the overloaded operator<< in output stream are not. A statement like

    std::cout << "hello" << std::endl;
    

    might have problem in multi-thread application, but something like

    printf("%s%s", "hello", "\n");
    

    is fine.

提交回复
热议问题