c++ - 命名空间中的函数模板特化

标签 c++ templates c++11 g++ clang++

我想特化一个函数模板。此函数在命名空间中声明:

namespace foo
{
   template <int>
   void function();
}

(为简单起见,模板基于int,而在我的生产代码中,它是一个enum class,但这是同一个问题。相同适用于基于类型的模板)

现在我想针对特定值专门化它:

template <>
void foo::function<0>()
{
}

使用 g++ -std=c++11(版本 4.6、4.7、4.8 和 4.9)编译失败:

specialization of ‘template void foo::function()’ in different namespace [-fpermissive]

clang++ -std=c++11 接受此代码。

g++ 也接受以下部分:

namespace foo
{
   template <>
   void function<0>()
   {
   }
}

谁是对的,gcc 还是 clang?

最佳答案

根据标准,§14.7.3/2,强调我的:

An explicit specialization shall be declared in a namespace enclosing the specialized template. An explicit specialization whose declarator-id 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.

你必须输入 template<> function<0>();namespace foo .但是,该规则仅适用于未限定的 declarator-id。当您提供 qualified-id(如 foo::function<0> )时,我认为该条款不应适用,这使得 clang 在这里是正确的。

例如,给定 function声明了这个问题,我希望得到以下结果:

namespace foo {
    template <> void function<0>(); // valid: unqualified explicit specialization
                                    // in the nearest enclosing namespace of the 
                                    // template
}

namespace bar {
    template <> void function<1>(); // invalid: unqualified explicit specialization
                                    // in the wrong namespace
}

struct baz {
    template <> void function<2>(); // invalid: unqualified explicit specialization
                                    // not in namespace scope
};

template <> void foo::function<3>(); // valid: qualified explicit specialization
                                     // is in a namespace, and id is qualified

template <> void bar::function<4>(); // invalid: there is no bar::function
                                     // to specialize

关于c++ - 命名空间中的函数模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28071129/

相关文章:

c++ - 打开 GL : is this the right way of using VBO IBO and VAO

c++ - 使用类作为具有前向声明的模板化类的模板参数

c++ - std::vector<bool> 是如何声明/定义的?

c++ - 取消引用临时的 unique_ptr

c++ - 模板中的默认参数 -> 模板参数涉及模板参数

c++ - 为什么 std::unique_ptr 没有 const get 方法?

c++ - boost 获取锁失败

c++ - 如何从字符串中每行输出一个单词

c++ - g++ arm-none-eabi 从 4.9 升级到 gcc 8.2。生成的二进制文件不再适合闪存

c++ - 非模板的模板定义