GCC错误:非命名空间范围的显式特化

Rya*_*yan 27 c++ gcc templates

我试图移植以下代码.我知道标准不允许在非namescape范围内进行显式特化,我应该使用重载,但我找不到在这种特殊情况下应用这种技术的方法.

class VarData
{
public:
    template < typename T > bool IsTypeOf (int index) const
    {
        return IsTypeOf_f<T>::IsTypeOf(this, index); // no error...
    }

    template <> bool IsTypeOf < int > (int index) const // error: explicit specialization in non-namespace scope 'class StateData'
    {
        return false;
    }

    template <> bool IsTypeOf < double > (int index) const // error: explicit specialization in non-namespace scope 'class StateData'
    {
        return false;
    }
};
Run Code Online (Sandbox Code Playgroud)

CB *_*ley 41

您只需将成员模板的专业化移到类主体之外.

class VarData
{
public:
    template < typename T > bool IsTypeOf (int index) const
    {
        return IsTypeOf_f<T>::IsTypeOf(this, index);
    }
};

template <> bool VarData::IsTypeOf < int > (int index) const
{
    return false;
}

template <> bool VarData::IsTypeOf < double > (int index) const
{
    return false;
}
Run Code Online (Sandbox Code Playgroud)

  • 我应该补充一点,为函数添加inline关键字是非常重要的,这些函数在类范围之外声明,至少在头文件中定义了模板类函数.否则链接器将无法工作...... (29认同)
  • @Ryan SD,您的意思是正确的专业化应该写成“模板&lt;&gt;内联bool VarData :: IsTypeOf &lt;int&gt;(int index)const {return false;}”和`模板&lt;&gt;内联bool VarData :: IsTypeOf &lt;double&gt;( int index)const {return false;}`? (2认同)

Naw*_*waz 6

将类外的特化定义为:

template <> 
bool VarData::IsTypeOf < int > (int index) const 
{  //^^^^^^^^^ don't forget this! 
     return false;
}

template <> 
bool VarData::IsTypeOf < double > (int index) const 
{   //^^^^^^^ don't forget this!
     return false;
}
Run Code Online (Sandbox Code Playgroud)