TeenyTinySparkles
TeenyTinySparkles

Reputation: 419

Namespace refactoring in C++

I am refactoring namespaces of small part of a large project. So I have refactored following 2 files which had Oldname as the namespace to 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)
{
--------
}
}

Now I am resolving this file 2 which has dependencies with the above file. I do not want to change the namespace of this file, but just modify the functions that depend on the above files.

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)

}
}

I tried to make it as follows,

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

However, I get the following error,

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

Can someone help how to resolve this error?

Upvotes: 1

Views: 376

Answers (1)

JaMiT
JaMiT

Reputation: 16869

From cppreference.com (emphasis added):

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

Given this rule, the definition of ::x::y::z::abc::funcA is allowed

  • in the definition of the class (::x::y::z::abc),
  • in namespace ::x::y::z,
  • in namespace ::x::y,
  • in namespace ::x, or
  • in the global namespace.

It is not allowed in any other namespaces. In particular, it is not allowed in the namespace Oldname. To resolve this error (without introducing namespace x to file2.cpp), take your definition out of Oldname and put it in the global namespace. Or maybe re-think how your namespaces are set up.

Upvotes: 1

Related Questions