C++中的命名空间重构

Namespace refactoring in C++

我正在重构大型项目中一小部分的命名空间。所以我重构了以下 2 个文件,这些文件将 Oldname 作为命名空间为 x::y::z

file1.hpp

namespace x::y::z
{

Class abc
{
public:
       void funcA(type1 arg1, type2 arg2)   
}

file1.cpp

#include "file1.hpp"

namespace x::y::z
{
void abc::funcA(type1 arg1, type2 arg2)
{
--------
}
}

现在我正在解析与上述文件有依赖关系的文件2。我不想改变这个文件的命名空间,只是修改依赖于上述文件的函数。

file2.cpp

#include "file1.hpp"

namespace Oldname
{
 void abc::funcA(type1 arg1, type2 arg2)
{
      mock("txt")
         .actualCall("abc.funcA")
         .withParameter("arg1", arg1)
         .withParameter("arg2", arg2)

}
}

我试着做了如下,

namespace Oldname
{
   void x::y::z::abc::funcA(type1 arg1, type2 arg2)
{
      mock("txt")
          .actualcall("abc.funcA")
          .withParameter("arg1",arg1)
          .withParameter("arg2",arg2)
}
}

但是,我收到以下错误,

error: cannot define or redeclare 'funcA' here because namespace 'Oldname' does not enclose namespace 'abc'

有人可以帮助解决这个错误吗?

来自 cppreference.com(强调已添加):

Out-of-namespace definitions and redeclarations are only allowed after the point of declaration, only at namespace scope, and only in namespaces that enclose the original namespace (including the global namespace) and they must use qualified-id syntax

鉴于此规则,::x::y::z::abc::funcA 的定义是允许的

  • 中定义了class(::x::y::z::abc),
  • 在命名空间 ::x::y::z
  • 在命名空间 ::x::y
  • 在命名空间 ::x 中,或
  • 在全局命名空间中。

不允许在任何其他命名空间中使用。特别是在命名空间 Oldname 中是不允许的。要解决此错误(不将 namespace x 引入 file2.cpp),请将您的定义从 Oldname 中取出并将其放入全局名称空间中。或者重新考虑您的命名空间是如何设置的。