C++ crazy typedef : what is the point of allowing this syntax by the Standard?

依然范特西╮ 提交于 2019-12-06 18:38:14

问题


The old familiar one:

typedef int cute_int; //cute : common and familiar syntax. 

This syntax is perfect. No problem.

Now, when we can write typedefs like above, then what is the point of allowing this syntax:

int typedef crazy_int; //crazy : uncommon and unfamiliar syntax.

Just to confuse programmers? Is this syntax even needed anywhere (when in fact we've the previous one)? What do you think from the compilers' point of view? Do they find it cute or crazy? Or it doesn't matter to the compilers at all?


By the way, this code came from here : Use of typename keyword with typedef and new

In case if you're wondering if that is syntax error, then check out the working code here at ideone.


回答1:


"The flip side of this is that you have to deal with old mistakes and with compatibility problems. For example, I consider the C declarator syntax an experiment that failed. Nevertheless, I adopted it for C++. The alternatives and improvements I considered at the time would not have improved matters. I rate is as a minor problem. The more serious problem is to maintain closeness of language definitions as C evolves." - Bjarne Stroustrup




回答2:


The question is "why it confuses you?"

The syntax comes from the grammar of declaration specifiers in C++, which is very general, and used for many things in C++. The order of declaration specifiers doesn't matter. Look at these:

int virtual f() const, *g(int);
int ptr1, *ptr2;
int typedef const *name1, name2;

These are equivalent to:

virtual int f() const;
virtual int* g(int);
int ptr1;
int *ptr2;
typedef const int* name1;
typedef const int name2;

If you look at them long enough you can find that the syntax is actually uniform and logical. Also reading the grammar of C++ may help.




回答3:


I was not aware of this syntax, though my g++ seems to accept it... but from a compiler standpoint, it makes parsing things harder: when you encounter an int token, you don't know if you're parsing a type definition (and a typedef is about to happen) or you're parsing a variable/function definition...

The only sense it makes to have A typedef B is if you consider typedef to be a binary operator (in the sense of a type assignment as A = B).




回答4:


I'm not sure that this is allowed by standart. But as we know there is a lot of things in c++ that allowed but have ilogical syntax. For instance this kind of things 1[a], "hello"[2];// ...



来源:https://stackoverflow.com/questions/4422816/c-crazy-typedef-what-is-the-point-of-allowing-this-syntax-by-the-standard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!