An old code base I'm refactoring has a rather unorthodox way to access n dimensional vectors by overloading the ()
operator instead of the []
operator.
To illustrate, suppose Vec is a class that overloads both operators for indexing purpose of an internal list of doubles.
Vec v, w;
int index = 651;
double x = v(index); // they index like this ..
double y = w[index]; // .. instead of like normally..
I can only think of one good reason why you would do this: The operator[]
requires an argument of type size_t
which may or may not be uint64
depending on the platform. On the other hand, the index type used in the code is mostly int
, which would mean a lot of implicit/explicit type casting when indexing. The code is extremely indexing heavy, so I'm quite hesitant to change this.
Does this really makes any sense for todays modern compilers and 64bit platforms? I quickly whipped up a test on https://godbolt.org/ You can try it out here here
I was primarily concerned with the latest x64 gcc and Visual Studio compilers, but the difference shows when compiling in x86-64 gcc (11.2). Gcc adds a cdqe
instruction for the ()
operator, which we know may be less efficient.
I am a bit puzzled. Why would one make this choice?
Update
As explained in the answers, my assumption about operator []
being locked to size_t
type size was incorrect. If you index with int
instead of uint64
indices, the compiled code is nearly the same, save using different registers and constants.
The idea to provide multiple indices for multiple dimensions with ()
is quite a nice one, I must say. Wasn't actually used anywhere in the codebase, so I think it's just better to replace it with []
. I'm also happy to see it handled by the proper indexing operator instead in future versions of C++.