非命名空间范围内的显式特化

Explicit specialization in non-namespace scope(非命名空间范围内的显式特化)
本文介绍了非命名空间范围内的显式特化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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() 转发到一个可能专门的免费函数:

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

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Could I ever want to access the address zero?(我可以想访问地址零吗?)
C++ Access derived class member from base class pointer(C++ 从基类指针访问派生类成员)
Weird Behaviour with const_cast(const_cast 的奇怪行为)
Are pointer variables just integers with some operators or are they quot;symbolicquot;?(指针变量只是带有某些运算符的整数还是“符号?)
Modifying a char *const string(修改 char *const 字符串)
Modifying a const int in C++(修改 C++ 中的 const int)