20

Is this standard in C++? In C#, I liked declaring nested namespaces like this:

namespace A.B 
{
    class X
    {
    };
}

The alternative was this, which is a little uglier:

namespace A
{
    namespace B
    {
        class X
        {
        };
    }
}

In C++, I wanted to see if it had a similar feature. I ended up finding this works:

namespace A::B
{
    class Vector2D
    {
    }
}

Notice the ::.

I'm curious if this is standard C++ or if this is a MS feature. I can't find any documentation on it. My ancient C++98 reference book doesn't mention it, so I wonder if it's an extension from Microsoft or a new feature.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Bob
  • 327
  • 3
  • 12
  • 1
    **Off-topic** since asking about external resources. See some [C++ reference](http://en.cppreference.com/w/cpp) site and read some C++ standard like [n3337](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf) – Basile Starynkevitch Jun 17 '18 at 06:55
  • 3
    It's a new feature in C++17, [mentioned in this answer](https://stackoverflow.com/a/38060437/1848654). – melpomene Jun 17 '18 at 06:57
  • I believe I found the answer here: http://en.cppreference.com/w/cpp/language/namespace "namespace ns_name::name (since C++ 17)" – Bob Jun 17 '18 at 07:02
  • Too bad Unreal only supports C++ 11 at this moment, but good to know for other projects. Thanks. – Bob Jun 17 '18 at 07:05
  • @Bob - Unreal? Isn't it a set of API's in C++ for a game engine? What does that have to do with compiler support? – StoryTeller - Unslander Monica Jun 17 '18 at 07:06
  • Last I heard UE4 only supports C++ 11 right now. I'm not sure on the details. I'm starting to think the version is independent of Unreal given what you said. – Bob Jun 17 '18 at 07:15

1 Answers1

28

Yes, this is legal C++ 17 syntax. It is, however, not called embedded namespace, but nested namespace.

namespace ns_name::name (8) (since C++17)

[...]

8) nested namespace definition: namespace A::B::C { ... } is equivalent to namespace A { namespace B { namespace C { ... } } }.

idmean
  • 14,540
  • 9
  • 54
  • 83