C++11 中有一个用于创建类型别名的新语法 using
。可以使用,其中typedef
被使用,并且可以被模板化。 explanation这有利于using
,像这样:
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
Vect<T>
as a synonym forstd::vector<T,MyAllocator<T>>
. With that reading, the new syntax for aliasing seems reasonably logical.
但是,我不明白。我们对类、函数使用模板,并且没有为它们提供单独的关键字。那为什么我们有一个单独的关键字 typedef
?
即:
class Foo {
};
template <typename>
class Bar {
};
我们使用class
对于两者Foo
和Bar
,和Foo
是一个实际的类,但是 Bar
是一个模板,类的“集合”。
有人可以解释一下吗?
最佳答案
除了(IMO)更大的可读性参数之外,别名模板不仅仅是别名(就像 typedef 一样,您无法以任何方式区分 typedef 与其别名类型):它们真正代表了一系列类型,例如,您可以写:
template<class T>
using foo = ...;
template<template<typename> class TT> void bar();
bar<foo>();
所以 foo 不仅仅是一个别名,它是一个不同的野兽;使用 typedef 可能会让人感到困惑......我认为这就是“Vec 不是类型的别名,并且不应该被视为 typedef 名称”的含义。
关于c++ - "using"创建类型别名的论点是否已经确定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47016563/