difference between 'typedef' and 'using' in C++11

What is the difference between ‘typedef’ and ‘using’ in C++11

Apart from ‘using’ can be used within template alias-declaration, they have the same semantics according to the standard:

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.

Interesting points

What do you think will happen in the following code:

typedef int myInt;
typedef double myInt;

// The above code will cause the compiler complaining:
// error: conflicting declaration 'typedef double myInt'
// note: previous declaration as 'typedef int myInt'

typedef int myInt;
typedef int myInt;

// The above code will compile fine. The compiler is happy.
// This means re-alias is allowed.

using myInt = int;
using myInt = double;

// The above code will cause the compiler complaining:
// error: conflicting declaration 'using myInt = '
// note: previous declaration as 'using myInt = int'

using myInt = int;
using myInt = int;

// The above code will compile fine. The compiler is happy.

what if we mix them? Consider the following code:

using myInt = int;
typedef int myInt;

// The above code compile fine. Again it tells us 'using' and 'typdef' have the same semantics.

using myInt = int;
typedef double myInt;

// As you can guess, the compiler is furious about this:
// error: conflicting declaration 'typedef double myInt'
// note: previous declaration as 'using myInt = int'

Conclusion

Alias-declaration is introduced in C++11. beside ‘using’ can be used for template alias-declaration, ‘typedef’ and 'using 'basically have the same semantics.
But ‘using’ is a strong recommendation. Because it can do what typedef do and also can do what typedef can not do. Another thing should be noted:
it seems some compiler using ‘using’ results in faster link times, because the compiler generates shorter symbol names.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值