为什么可以在命名空间块之外定义 template 而不能定义 template<>?

2024-04-25

这是一些无法编译的代码。

namespace ns
{
    class foo
    {
        template <typename T> int bar (T *);
    };
}

template <typename T>
int ns :: foo :: bar (T*) // this is OK
{
    return 0;
}

template <>
int ns :: foo :: bar <int> (int *) // this is an error
{
    return 1;
}

错误是:“与‘template int ns::foo::bar(T*) 的定义不同的命名空间 [-fpermissive] 中‘template int ns::foo::bar(T*)’的专业化”

这是一个可以编译的版本:

namespace ns
{
    class foo
    {
        template <typename T> int bar (T *);
    };
}

template <typename T>
int ns :: foo :: bar (T*)
{
    return 0;
}

namespace ns
{
    template <>
    int foo :: bar <int> (int *)
    {
        return 1;
    }
}

为什么第二个定义必须在namespace ns {}当第一个很高兴地用限定名称定义时阻止?这只是语言设计中的疏忽还是有其他原因?


这里的问题不是定义,但是宣言。您不能从不同的命名空间在命名空间中注入声明,因此专业化must必须先在适当的命名空间中声明,然后才能defined在任何封闭的命名空间中。

基本模板的定义可以在外部命名空间中完成,因为它已经被定义了declared,因此外部命名空间中的代码提供了定义,但没有将任何声明注入到命名空间中。

Try:

namespace ns {
    class foo
    {
        template <typename T> int bar (T *);
    };
    template <>
    int foo::bar<int>(int*); // declaration
}
template <typename T>
int ns :: foo :: bar (T*) {
    return 0;
}
template <>
int ns :: foo :: bar <int> (int *) {
    return 1;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么可以在命名空间块之外定义 template 而不能定义 template<>? 的相关文章

随机推荐