寻求对内联命名空间的澄清

Seeking clarification on inline namespace

cppreference中找到以下文字:

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.

这些陈述意味着什么?有人可以通过一个简单的例子来解释吗?

考虑一个愚蠢的例子:

#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;
}

如果你运行这个,你会得到以下输出:

Specialized bar
Specialized bar
Generic bar

这是因为使用 int 调用 foo::bar 专门用于 foo,即使默认实现存在于 foo::v1.

这个例子是无用的,但考虑一下你想在外部库(包括 stl)中专门化 template 函数或 class 的场景。您不知道 vectorstd 还是 std::cxx11 的成员(libc++ 在很多方面使用 std::__1)。由于 inline namespace 是一种在 API 级别提供版本控制的方法(例如,您将 inline namespace 更改为 v2 并单独保留 v1),这让最终用户在不知道 inlined namespaces.

的细节的情况下进行专业化