Seeking clarification on inline namespace

601 Views Asked by At

In cppreference, the following text is found:

Each member of an inline namespace can be partially specialized , explicitly instantiated or explicitly specialized as if it were a member of the enclosing namespace.

Note: the rule about specializations allows library versioning: different implementations of a library template may be defined in different inline namespaces, while still allowing the user to extend the parent namespace with an explicit specialization of the primary template.

What do these statements imply? Can someone explain by means of a simple example?

1

There are 1 best solutions below

0
On BEST ANSWER

Consider a stupid example:

#include <iostream>

namespace foo {
    inline namespace v1 {
        template <typename T>
        void bar(T t) {
            (void) t;
            std::cout << "Generic bar\n";
        }
    }

    template <>
    void bar<int>(int v) {
        (void) v;
        std::cout << "Specialized bar\n";
    }
}

int main() {
    foo::bar(12);
    foo::v1::bar(12);
    foo::bar(12.0);
    return 0;
}

If you run this, you'll get the following output:

Specialized bar
Specialized bar
Generic bar

This is because calling foo::bar with an int is specialized in foo, even though the default implementation exists in foo::v1.

This example is useless, but consider a scenario where you wanted to specialize a template function or class in an external library (including the stl). You don't know if vector is a member of std or std::cxx11 (libc++ uses std::__1 for many things). Since an inline namespace is a way to provide versioning at the API level (e.g., you change your inline namespace to v2 and leave v1 alone), this lets end-users specialize without knowing the details of the inlined namespaces.