Real-world advantage of namespace aliases vs defines [closed]

荒凉一梦 提交于 2019-12-20 03:22:13

问题


EDIT: 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.

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

Take the code

#define MY_NAMESPACE my_namespace

versus

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.


回答1:


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.




回答2:


Generally speaking, the only advantage I see with namespace aliases is that they can be anywhere. Take the following example:

namespace a
{
    namespace that_is_a_great_namespace
    {
        namespace b = that_is_a_great_namespace;
    }
}

namespace that_is_a_great_namespace {}

You won't be able to define a macro that will convert a::that_is_a_great_namespace to a::b with no side effect. Here, that_is_a_great_namespace will also be converted to b. Namespace aliases help to resolve name conflicts in those cases.

However, if you already use #defines and it already works, refactoring your code for such a rare case may not be useful.



来源:https://stackoverflow.com/questions/14628665/real-world-advantage-of-namespace-aliases-vs-defines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!