c++ - "using"创建类型别名的论点是否已经确定?

标签 c++ templates alias typedef language-design

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 name Vec is a name for the family std::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 for std::vector<T,MyAllocator<T>>. With that reading, the new syntax for aliasing seems reasonably logical.

但是,我不明白。我们对类、函数使用模板,并且没有为它们提供单独的关键字。那为什么我们有一个单独的关键字 typedef

即:

class Foo {
};

template <typename>
class Bar {
};

我们使用class对于两者FooBar ,和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/

相关文章:

c++ - Qt QGraphicsScene items() 段错误

c++ - 无法访问属性 C++

c++ - 在类内声明模板化函数(通过容器类型)并在模板类之外通过容器类型定义它 -

bash - 在多个(新)选项卡中打开现有 Gvim 中的文件

c++ - 在多个声明中使用 auto 时,为什么需要为所有变量初始化?

c++:多文件c++项目中的相互引用结构

c++ - 无法推导 std::function 模板参数

C++ 模板特化冗余减少

bash - 灵活的SCP别名

bash - 别名导致错误 : syntax error near unexpected token `('