2

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

#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>() {
                        ~~^
4

1 回答 1

5

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

14.7.3 显式特化 [temp.expl.spec]

2 显式特化应在包含特化模板的命名空间中声明。declarator-id 或 class-head-name 未限定的显式特化应在模板的最近的封闭命名空间中声明,或者,如果命名空间是内联的(7.3.1),则应在其封闭命名空间集中的任何命名空间中声明。这样的声明也可以是一个定义。如果声明不是定义,则可以稍后定义特化(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;
}
于 2017-05-02T11:00:18.920 回答