I know that in C++11 we can now use using
to write type alias, like typedef
s:
typedef int MyInt;
Is, from what I understand, equivalent to:
using MyInt = int;
And that new syntax emerged from the effort to have a way to express "template typedef":
template< class T > using MyType = AnotherType< T, MyAllocatorType >;
But, with the first two non-template examples, are there any other subtle differences in the standard? For example, typedef
s do aliasing in a "weak" way. That is it does not create a new type but only a new name (conversions are implicit between those names).
Is it the same with using
or does it generate a new type? Are there any differences?
Definition on C++ using vs typedef. In C++, 'using' and 'typedef' performs the same task of declaring the type alias. There is no major difference between the two. 'Using' in C++ is considered to define the type synonyms.
typedef is limited to giving symbolic names to types only, whereas #define can be used to define an alias for values as well, e.g., you can define 1 as ONE, 3.14 as PI, etc. typedef interpretation is performed by the compiler where #define statements are performed by preprocessor.
We can have symbolic names to datatypes using typedef but not to numbers etc. Whereas with a macro, we can represent 1 as ONE, 3.14 as PI and many more. We can have a type name and a variable name as same while using typedef. Compiler differentiates both.
typedef is a reserved keyword in the programming languages C and C++. It is used to create an additional name (alias) for another data type, but does not create a new type, except in the obscure case of a qualified typedef of an array type where the typedef qualifiers are transferred to the array element type.
They are equivalent, from the standard (emphasis mine) (7.1.3.2):
A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With