C++ syntax understanding issue for ‘using’

I read technical documentation for some projects which are created with C++. I found a line of code that contains syntax I don’t understand:

using c = char (& (cClass::* [1]) (cClass(*)[2]) &)[3];

I see the using keyword here. That means we deal with an alias, but what does this line do? How can I understand it? I think this creates a named alias c and assigns the result of the expression on the right to it. But what is in this expression?

Answer

Here’s how your type is read, step by step. For the sake of clarity, below we declare a variable x.

T x[1]

x is an array (length 1) of type T

cClass::* x[1]

x is an array (length 1) of pointer-to-member inside cClass.

V (cClass::* x[1]) (U)

x is an array (length 1) of pointer-to-member-function inside cClass. Said member function takes U as argument and returns V.

V (cClass::* x[1]) (U) &

x is an array (length 1) of pointer-to-member-function inside cClass. Said member function takes U as argument and returns V, and can only be called on lvalues.

V & (cClass::* x[1]) (U) &

x is an array (length 1) of pointer-to-member-function inside cClass. Said member function takes U as argument and returns reference-to-V, and can only be called on lvalues.

V (& (cClass::* x[1]) (U) &)[3]

x is an array (length 1) of pointer-to-member-function inside cClass. Said member function takes U as argument and returns a reference to array (length 3) of V, and can only be called on lvalues.

Finally, to get your actual type

char (& (cClass::* x[1]) (cClass(*)[2]) &)[3]

we choose V = char, and U = (cClass(*)[2]), the latter being a pointer to array (length 2) of cClass.

More readable alternative:

using char3 = char [3];
using ptrTo2cClass = cClass(*)[2];
using ptrToMethod = char3 & (cClass::*) (ptrTo2cClass) &;
using c = ptrToMethod[1];

Leave a Reply

Your email address will not be published. Required fields are marked *