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

橙三吉。 提交于 2019-12-02 02:43:37

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.

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.

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