MooseTech
MooseTech

Reputation: 11

Multiple Namespaces In a Single File That Reference Each Other C++

I have been writing a c++ project, however I ran into a problem that arose when using namespaces. I have two namespaces that are declared in the same file as follows:

namespace base
{
     typedef unsigned char byte;

     std::vector<ext::longByte> arr;
}
namespace ext
{
     typedef unsigned int longByte;

     std::vector<base::byte> arr;
}

however when i compile this in VS it returns an error in the 5th line saying that "ext is not a valid namespace or class" despite the fact its declared right there.

Do namespaces need prototypes like functions?

Is there someway to solve this?

Thanks

Upvotes: 0

Views: 182

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409176

The "nice" thing about namespaces is that the can be extended. You can split namespace declarations and definitions into multiple parts.

This means you could first define the type-aliases in their respective namespace. Then you can define the vectors at a later point:

namespace base
{
     typedef unsigned char byte;
}

namespace ext
{
     typedef unsigned int longByte;
}

// Possible other code...
    
namespace base
{
     std::vector<ext::longByte> arr;
}

namespace ext
{
     std::vector<base::byte> arr;
}

A possibly "better" solution could be a redesign where you don't need circular dependencies like this.

Upvotes: 3

Related Questions