使用-声明现有名称空间类型与创建类型别名 [英] Using-declaration of an existing namespace type vs creating a type alias

查看:182
本文介绍了使用-声明现有名称空间类型与创建类型别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不是关于usingtypedef在创建类型别名方面的区别的问题.我想提供从代码块或函数内部的命名空间访问现有类型的方法.

This is not a question about the difference between using and typedef for creating type aliases. I would like to provide access to an existing type from a namespace inside a code block or a function.

我发现了两种不同的方式:

I found two different ways :

我可以使用using声明包含"类型:

I can "include" the type with a using declaration :

using typename mynamespace::mytype;

或者我可以创建一个类型别名:

Or I can create a type alias :

typedef mynamespace::mytype mytype;
using mytype = mynamespace::mytype; //C++11

  1. 有什么区别吗?
  2. 每种语法的优缺点是什么?
  3. 哪个是最常用/推荐的?

谢谢.

相关问题:推荐答案

有什么区别吗?

Is there any difference ?

命名空间中名称的类型别名可以出现在类中

A type alias for a name in a namespace can appear in a class

struct S { using mytype = mynamespace::mytype; };

,而使用声明则可能不会.

while a using-declaration may not.

每种语法的优缺点是什么?

What are the pros and cons of each syntax ?

如果要处理类范围,上一点是一个很大的缺点.

The previous point is a pretty big con if you are dealing with class scope.

除此之外,这两种方法非常相似.别名是一个新名称,恰好代表别名类型. using声明将类型的现有名称纳入范围.如果您同时使用mytype,则不会有任何区别.

Other than that the two approaches are pretty much similar. An alias is a new name that stands exactly for the type that is aliased. While a using declaration brings the existing name of the type into scope. If you use mytype for both, you won't notice a difference.

哪个是最常用/推荐的?

Which one is the most used/recommended ?

我对此是否达成共识表示怀疑.在必须使用时(类别范围)使用您必须使用的一种,否则,请遵循团队的风格指南.

I doubt there's consensus on this. Use the one you have to when you have to (class scope), but stick to your team's style guide otherwise.

这篇关于使用-声明现有名称空间类型与创建类型别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆