typedef vs using in C++

Declaring new aliases

There are two ways of declaring new type aliases in modern C++:

  • typedef
  • using

注意:两者都没有 create 新的 type,只是一个原来的 type 的一个 alias.

typedef

The first and traditional one is with the typedef keyword:

1
typedef [original-type] [your-alias];

For example:

1
2
typedef int Pixel;
typedef std::map<std::string, std::vector<std::string>> Map;

using

The other one, introduced in C++11, is with the using keyword:

1
using [your-alias] = [original-type];

For example

1
2
using Pixel = int;
using Map = std::map<std::string, std::vector<std::string>>;

using works best with templates

除了上面的用法,using 还可以用于 template,这是它比 typedef 多出来的一个用处。

typedef vs using

在用于普通的 type 的时候是一致的,没有区别。

在用于 template 的时候,只能用 using

可以认为 typedefusing 的一个子集,using 是 more preferable 的。

Where to put it

You can put type alias declarations — both performed with typedef or using — everywhere you wish: in namespaces, in classes and inside blocks (i.e. between { and }).

Note: Alias templates on the other hand follow the same rules of any other templated thing in C++: they cannot appear inside a block. They are actual template declarations, after all!

Reference