13

I'm reading template aliases here: http://en.cppreference.com/w/cpp/language/type_alias

And I'm wondering, even if it's written on the very first line of the page I linked, what's the difference between a typedef and a type alias (using mytype = T;)

Aren't they interchangeable?

Marco A.
  • 43,032
  • 26
  • 132
  • 246

2 Answers2

20

There is absolutely no difference between both.

If you take a look at the standard :

7.1.3 The typedef specifier [dcl.typedef ]

A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name. It has the same semantics as if it were introduced by the typedef specifier. In particular, it does not define a new type and it shall not appear in the type-id.

7.3.3 The using declaration [namespace.udecl]

If a using-declaration uses the keyword typename and specifies a dependent name (14.6.2), the name introduced by the using-declaration is treated as a typedef-name.


However from this page : http://en.cppreference.com/w/cpp/language/type_alias

It is said :

Type aliases are similar to typedefs, however, have the advantage of working with templates.

It seems that this

// template type alias
template<class T> using ptr = T*;
// the name 'ptr<T>' is now an alias for pointer to T
ptr<int> x;

is only possible with the using directive.


And do not forget that this is a C++11 feature. Some compilers do not support it yet.

Community
  • 1
  • 1
Pierre Fourgeaud
  • 14,290
  • 1
  • 38
  • 62
1

There is no difference.

typedef gives an alias name for the type.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331