Real-world advantage of namespace aliases vs defin

2019-02-27 02:31发布

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.

2条回答
欢心
2楼-- · 2019-02-27 02:37

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.

查看更多
Animai°情兽
3楼-- · 2019-02-27 02:50

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.

查看更多
登录 后发表回答