Inline namespace

suggest change

inline namespace includes the content of the inlined namespace in the enclosing namespace, so

namespace Outer
{
    inline namespace Inner
    {
        void foo();
    }
}

is mostly equivalent to

namespace Outer
{

    namespace Inner
    {
        void foo();
    }

    using Inner::foo;
}

The name Outer::Inner::foo and the name Outer::foo refer to the same entity.

The following calls are equivalent:

Outer::foo();
Outer::Inner::foo();

The alternative using namespace Inner; would not be equivalent for some tricky parts as template specialization:

For

#include <outer.h> // See below

class MyCustomType;
namespace Outer
{
    template <>
    void foo<MyCustomType>() { std::cout << "Specialization"; }
}
// outer.h
// include guard omitted for simplification
#include <iostream>

namespace Outer
{
    inline namespace Inner
    {
        template <typename T>
        void foo() { std::cout << "Generic"; }
    }
}
// outer.h
// include guard omitted for simplification
#include <iostream>

namespace Outer
{
    namespace Inner
    {
        template <typename T>
        void foo() { std::cout << "Generic"; }
    }
    using namespace Inner;
    // Specialization of `Outer::foo` is not possible.
    // It has to be a specialization of `Outer::Inner::foo`.
}

An inline namespace is a way to let several versions coexist and to make the inline one the default.

namespace MyNamespace
{
    // Inline the last version
    inline namespace Version2
    {
        void foo(); // New version
        void bar();
    }

    namespace Version1 // The old one
    {
        void foo();
    }

}

And with usage

MyNamespace::Version1::foo(); // old version
MyNamespace::Version2::foo(); // new version
MyNamespace::foo();           // default version: MyNamespace::Version2::foo()

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents