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

时间:2011-04-25 09:58:24

标签: c++ templates gcc

我正在尝试移植以下代码。我知道标准不允许在非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;
    }
};

2 个答案:

答案 0 :(得分:38)

您只需将成员模板的专业化移到课堂体外。

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

答案 1 :(得分:5)

将类外的特化定义为:

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