真实世界中命名空间别名的优点vs定义 [英] Real-world advantage of namespace aliases vs defines

查看:182
本文介绍了真实世界中命名空间别名的优点vs定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:我打算重构一些代码,并用命名空间别名替换 define 。我不能这样做,只是因为宏是邪恶的。我需要解释为什么我要进行更改, 如果我不这样做可能会出错。

I'm planing to refactor some code, and replace the define with a namespace alias. I can't do this though just because "macros are evil". I need to explain why I want to make the change and what can go wrong if I don't.

抛开macros is evil的立场,在命名空间别名上的 #define

Leaving aside the stance that "macros are evil", what are the downfalls of #define over a namespace alias?

取代码

#define MY_NAMESPACE my_namespace

namespace MY_NAMESPACE = my_namespace;

具有别名的原因不在问题的范围内。你还可以假定命名空间的名称是唯一的,它不会出现在任何其他地方(即它只是引用该命名空间,它不能 - 不是现在,不是在未来 - 引用一个变量或类,

The reason for having aliases is not in the scope of the question. You can also assume the name of the namespace is unique enough that it doesn't appear anywhere else (i.e. it just refers to that namespace, it can't - not now, not in the future - refer to a variable or a class or whatever), so there can be no ambiguity there.

推荐答案

在这种特殊情况下,这取决于。如果使用命名空间别名
做的伎俩,一切意味着更喜欢它的宏,所有的
通常的原因。但两者做了完全不同的事情。您
无法使用其别名打开命名空间,即:

In this particular case, it depends. If using a namespace alias does the trick, by all means prefer it to macros, for all of the usual reasons. But the two do radically different things. You cannot open a namespace using its alias, i.e.:

namespace XYZ_ver1 {}
namespace XYZ = XYZ_ver1;

namespace XYZ {     //  Illegal!
}

事实上,你可以在命名空间出现之前定义宏
。如果你需要这个,那么
你需要使用一个宏。

This works with a macro; in fact, you can define the macro before the namespace has ever appeared. If you need this, then you need to use a macro.

这篇关于真实世界中命名空间别名的优点vs定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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