【问题标题】:How to explicitly specialize a function template from within another namespace?如何从另一个命名空间中显式地专门化一个函数模板?
【发布时间】:2017-05-02 10:18:47
【问题描述】:

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

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

【问题讨论】:

标签: c++ templates namespaces template-specialization explicit-specialization


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-05
    • 2015-03-12
    • 2019-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多