模板typedef的新"使用"语法解决了什么问题?

sho*_*osh 16 c++ templates typedef c++11 template-aliases

在C++ 11中,您可以通过执行类似的操作来创建"类型别名"

template <typename T>
using stringpair = std::pair<std::string, T>;
Run Code Online (Sandbox Code Playgroud)

但这与您期望的模板typedef看起来有所不同:

template <typename T>
typedef std::pair<std::string, T> stringpair;
Run Code Online (Sandbox Code Playgroud)

所以这提出了一个问题 - 为什么他们需要提出一个新的语法?什么是旧的typedef语法不起作用?

我意识到最后一点没有编译,但为什么不能编译?

dor*_*ege 18

我只想提到stroustrup本人:

http://www.stroustrup.com/C++11FAQ.html#template-alias

关键字using用于获取线性表示法"名称后跟其引用的内容".我们尝试使用传统的和复杂的typedef解决方案,但在我们确定一个不那么模糊的语法之前,我们从未设法获得完整且连贯的解决方案.


Tem*_*Rex 9

从WG21提案N1489模板别名(由Stroustrup和Dos Reis提供):

有人建议(重新)使用typedef文章[4]中的关键字来引入模板别名:

 template<class T> 
 typedef std::vector<T, MyAllocator<T> > Vec;
Run Code Online (Sandbox Code Playgroud)

该符号具有使用已知的关键字引入类型别名的优点.然而,它还显示了一些不利之处,其中混淆使用已知的关键字在别名未指定类型但模板的上下文中为类型名称引入别名; Vec不是类型的别名,不应该用于typedef-name.名称Vec是家族的名称, std::vector<o, MyAllocator<o> > 其中项目符号是类型名称的占位符.因此,我们不建议使用typedef语法.

另一方面这句话

template<class T> 
using Vec = std::vector<T, MyAllocator<T> >;
Run Code Online (Sandbox Code Playgroud)

可以被读/解释为:从现在开始,我将Vec<T>用作同义词std::vector<T, MyAllocator<T> >.通过该读取,用于别名的新语法似乎合理逻辑.

上述引文中提到的论文[4]是先前提议的WG21 N1406建议加入C++:Typedef模板(由Herb Sutter 撰写).它使用不同的语法(typedefvs using)以及不同的命名法(typedef templates vs template aliases).赫伯提出的语法并没有成功,但有时可以在非正式讨论中找到命名法.

  • 虽然在解释中有点迂腐,但我认为这里有一个非常直接的论点:模板的typedef不会定义类型,而是模板. (3认同)