Home >Backend Development >C++ >What's the Difference Between C 's `typedef` and `using` Keywords for Type Aliases?

What's the Difference Between C 's `typedef` and `using` Keywords for Type Aliases?

Linda Hamilton
Linda HamiltonOriginal
2024-12-21 04:53:13602browse

What's the Difference Between C  's `typedef` and `using` Keywords for Type Aliases?

What is the Difference Between 'typedef' and 'using' in C ?

In C 11, the 'using' keyword can be used to create type aliases similar to the traditional 'typedef' keyword. While both syntaxes achieve the same result of assigning a new name to an existing type, there are subtle differences in their semantics to consider.

Is 'using' Equivalent to 'typedef'?

According to the C standard (7.1.3.2), 'using' introduces a typedef-name with identical semantics as if it were defined using 'typedef'. This means that 'using' does not create a new type but instead provides an alternative name for an existing type. Conversions between these names are implicit.

Differences in Semantics

Despite their similar syntax and semantics, the 'using' keyword differs from 'typedef' in the following ways:

  • Weak Aliasing: 'typedef' creates a "weak" alias, meaning that it does not redefine the original type. 'using', on the other hand, cannot be used to create weak aliases.
  • Template Type Aliases: 'using' can be used to create template type aliases, while 'typedef' cannot. For example:
template<typename T>
using MyType = AnotherType<T, MyAllocatorType>;

The above is the detailed content of What's the Difference Between C 's `typedef` and `using` Keywords for Type Aliases?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn