如何从另一个命名空间中显式特化函数模板?

How to explicitly specialize a function template from within another namespace?

出于可读性原因,我想专门化一个函数模板,使其接近在命名空间内声明的 class 的定义:

#include <iostream>

template<typename T> void my_function() {
    std::cout << "my_function default" << std::endl;
}

namespace Nested {
    class A {};
    template<> void my_function<A>() {
        std::cout << "my_function specialization for A" << std::endl;
    }
}

但是,使用上面的代码,我从 clang++ 4.0 得到以下错误:

 error: no function template matches function template specialization 'my_function'

这似乎是一个命名空间问题。我怎样才能让上面的工作(不将模板函数专业化移出 Nested 命名空间)?

编辑:我也尝试在专业化中添加 ::my_function

test.cpp: error: definition or redeclaration of 'my_function' cannot name the global scope
        template<> void ::my_function<A>() {
                        ~~^

这是不可能的,特化必须与模板本身位于同一个命名空间中:

14.7.3 Explicit specialization [temp.expl.spec]

2 An explicit specialization shall be declared in a namespace enclosing the specialized template. An explicit specialization whose declarator-id or class-head-name is not qualified shall be declared in the nearest enclosing namespace of the template, or, if the namespace is inline (7.3.1), any namespace from its enclosing namespace set. Such a declaration may also be a definition. If the declaration is not a definition, the specialization may be defined later (7.3.1.2).

所以你必须像这样重写你的代码:

namespace Nested {
class A {};
} // namespace Nested

template<> void my_function<Nested::A>() {
    std::cout << "my_function specialization for A" << std::endl;
}