C ++ 11中“typedef”和“using”有什么区别?

我知道在C ++ 11中,我们现在可以using typedef s using类型别名:

 typedef int MyInt; 

据我所知,相当于:

 using MyInt = int; 

这种新的语法来自于努力去表达“ template typedef ”:

 template< class T > using MyType = AnotherType< T, MyAllocatorType >; 

但是,在前两个非模板的例子中,标准还有其他的细微差别吗? 例如, typedef以“弱”方式进行别名。 也就是说,它不会创建新的类型,而只是一个新的名称(这些名称之间的转换是隐含的)。

它是using相同还是生成一个新的类型? 有什么区别?

它们是相同的,从标准(重点是我的)(7.1.3.2):

typedef-name也可以通过别名声明来引入。 using关键字后面的标识符变为typedef-name,标识符后面的可选attribute-specifier-seq属于该typedef-name。 它具有与由typedef说明符引入的相同的语义。 特别是它没有定义一个新的类型,它不会出现在type-id中。

在模板中使用using语法有一个优点。 如果您需要抽象类型,而且还需要保留模板参数以后可以指定。 你应该写这样的东西。

 template <typename T> struct whatever {}; template <typename T> struct rebind { typedef whatever<T> type; // to make it possible to substitue the whatever in future. }; rebind<int>::type variable; template <typename U> struct bar { typename rebind<U>::type _var_member; } 

但是使用语法简化了这个用例。

 template <typename T> using my_type = whatever<T>; my_type<int> variable; template <typename U> struct baz { my_type<U> _var_member; } 

除此之外,它们基本上是一样的

The alias declaration is compatible with templates, whereas the C style typedef is not.