明显的,类型别名和模板类型别名在语义上等同于typedef,并且是支持模板的typedef扩展。为什么针对这些扩展需要创建带有using
关键字的新语法,而不是使用typedef进行第一步并使用带有 typedef
词的某些语法扩展。
注意:这不是“使用和typedef之间的区别”问题的克隆。我知道using
的优点在于定义一族typedef
。我问的是标准人员为什么决定使用using
关键字来进行此扩展,而不是typedef
关键字。这似乎只会增加语言中的混淆。
明显的,类型别名和模板类型别名在语义上等同于typedef,并且是支持模板的typedef扩展。为什么针对这些扩展需要创建带有using
关键字的新语法,而不是使用typedef进行第一步并使用带有 typedef
词的某些语法扩展。
注意:这不是“使用和typedef之间的区别”问题的克隆。我知道using
的优点在于定义一族typedef
。我问的是标准人员为什么决定使用using
关键字来进行此扩展,而不是typedef
关键字。这似乎只会增加语言中的混淆。
using
而不是扩展typedef
的说法:using
是为了获得一个线性符号“名称后跟其所指代的内容”。我们曾试过传统且复杂的typedef
解决方案,但直到我们采用了一种不那么晦涩的语法,才成功地获得了一个完整而连贯的解决方案。typedef
。
In addition to being important in connection with templates, type aliases can also be used as a different (and IMO better) syntax for ordinary type aliases:
using PF = void (*)(double);
他说得很正确,这看起来非常简洁。相比之下,typedef将会非常复杂,因为名称可能会出现在中间:
typedef void(*PF)(double);
这里有一个来自他们提案的解释(见第4页),更加深入:
It has been suggested to (re)use the keyword typedef — as done in the paper [4] — to introduce template aliases:
template<class T> typedef std::vector<T,MyAllocator<T>> Vec;
That notation has the advantage of using a keyword already known to introduce a type alias. However, it also displays several disadvantages among which the confusion of using a keyword known to introduce an alias for a type-name in a context where the alias does not designate a type, but a template;
Vec
is not an alias for a type, and should not be taken for a typedef-name. The nameVec
is a name for the familystd::vector<*,MyAllocator<*>>
- where the asterisk is a placeholder for a type-name. Consequently, we do not propose the "typedef" syntax.
template<class T> using Vec = std::vector<T,MyAllocator<T>>;
can be read/interpreted as: from now on, I'll be using
Vec<T>
as a synonym forstd::vector<T,MyAllocator<T>>
. With that reading, the new syntax for aliasing seems reasonably logical.
所以他基本上有两个观点:
using
模板成为一组类型,而不是一个类型,因此 typedef
是“错误”的using
几乎可以被读作英语句子using
应该替代 typedef。语法更清晰明了。 - ApproachingDarknessFishvoid(*)(double)
示例的 typedef 是什么样子的。 :) - jalftypedef void(*)(double) PF;
。这几乎和 using
一样清晰。模板 typedefs - 好吧,你可以使用它,就像函数指针 typedefs 一样...回到函数指针,实际上,在定义变量时我感觉很像:为什么不是 int(*)(double) callback;
?我知道,哲学最终与 char *a, b, *c;
相同。这是我能够阅读的东西,但我从未与之交朋友,并且永远不会在我的代码中使用它,因为我的个人阅读方式不同... - Aconcaguatemplate<typename T> typedef X<T,int> Xi;
using
语法,并指出以下内容:
他们还说:请注意,我们特别避免使用“typedef template”一词,并引入了涉及“using”和“=”的新语法以帮助避免混淆:我们在此处不定义任何类型,我们正在引入一个类型的同义词(即别名),该类型是涉及模板参数的类型标识符(即类型表达式)的抽象。
这种语法随后被 Gabriel Dos Reis 和 Bjarne Stroustrup 采纳,并在最终提案 N2258 中使用。有关语法进行了两次草案投票。绝大多数人投票支持避免使用typedef模板语法,而支持“=”语法。第二次投票表明,与“alias”或本提案草案中缺少任何关键字相比,“using”关键字更受欢迎。使用任何关键字的动机部分源于希望使用可能与上面简要概述的非模板别名方向兼容的语法。
using =
在语法层面上反映了其语义。 - dyp