Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

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?

question from:https://stackoverflow.com/questions/66617894/c-syntax-understanding-issue-for-using

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...