非命名空间范围中的显式专门化 [英] Explicit specialization in non-namespace scope

查看:111
本文介绍了非命名空间范围中的显式专门化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

template<typename T>
class CConstraint
{
public:
    CConstraint()
    {
    }

    virtual ~CConstraint()
    {
    }

    template <typename TL>
    void Verify(int position, int constraints[])
    {       
    }

    template <>
    void Verify<int>(int, int[])
    {   
    }
};

在g ++下编译此语句会产生以下错误:

Compiling this under g++ gives the following error:

非命名空间作用域中的显式专门化'class CConstraint'

Explicit specialization in non-namespace scope 'class CConstraint'

在VC中,它编译得很好。任何人都可以让我知道解决方法?

In VC, it compiles fine. Can anyone please let me know the workaround?

推荐答案

VC ++在这种情况下不符合 - 显式专门化必须在命名空间范围。 C ++ 03,§14.7.3/ 2

VC++ is non-compliant in this case - explicit specializations have to be at namespace scope. C++03, §14.7.3/2:


其中模板是成员,或者对于成员模板,在封闭类或封闭类模板是其成员的命名空间中。

成员函数,成员类或静态数据的显式特化类模板的成员应在类模板是其成员的命名空间中声明。

An explicit specialization shall be declared in the namespace of which the template is a member, or, for member templates, in the namespace of which the enclosing class or enclosing class template is a member.
An explicit specialization of a member function, member class or static data member of a class template shall be declared in the namespace of which the class template is a member.

此外,由于C ++ 03,§14.7.3/ 3 ,不能专门化成员函数而不明确专门化包含类,因此一个解决方案是让 Verify / code>转发到一个可能是专门的免费函数:

Additionally you have the problem that you can't specialize member functions without explicitly specializing the containing class due to C++03, §14.7.3/3, so one solution would be to let Verify() forward to a, possibly specialized, free function:

namespace detail {
    template <typename TL> void Verify     (int, int[]) {}
    template <>            void Verify<int>(int, int[]) {}
}

template<typename T> class CConstraint {
    // ...
    template <typename TL> void Verify(int position, int constraints[]) {
        detail::Verify<TL>(position, constraints);
    }
};

这篇关于非命名空间范围中的显式专门化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆