Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ GCC错误:非命名空间范围中的显式专门化_C++_Templates_Gcc - Fatal编程技术网

C++ GCC错误:非命名空间范围中的显式专门化

C++ GCC错误:非命名空间范围中的显式专门化,c++,templates,gcc,C++,Templates,Gcc,我正在尝试移植以下代码。我知道该标准不允许在非命名空间范围内显式专门化,我应该使用重载,但我就是找不到一种方法在这种特殊情况下应用这种技术 class VarData { public: template < typename T > bool IsTypeOf (int index) const { return IsTypeOf_f<T>::IsTypeOf(this, index); // no error... }

我正在尝试移植以下代码。我知道该标准不允许在非命名空间范围内显式专门化,我应该使用重载,但我就是找不到一种方法在这种特殊情况下应用这种技术

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;
    }
};
class变量数据
{
公众:
模板bool IsTypeOf(int索引)常量
{
返回IsTypeOf_f::IsTypeOf(this,index);//无错误。。。
}
模板bool IsTypeOf(int index)const//error:非命名空间作用域“class StateData”中的显式专门化
{
返回false;
}
模板bool IsTypeOf(int index)const//error:在非命名空间范围“class StateData”中显式专门化
{
返回false;
}
};

将类外的专门化定义为:

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;
}
模板
bool VarData::IsTypeOf(int索引)常量
{/^^^^^^^^^^^^^别忘了这一点!
返回false;
}
模板
bool VarData::IsTypeOf(int索引)常量
{/^^^^^^^^^^^别忘了这一点!
返回false;
}

只需将成员模板的专门化移到类主体之外即可

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;
}
class变量数据
{
公众:
模板bool IsTypeOf(int索引)常量
{
返回IsTypeOf_f::IsTypeOf(此,索引);
}
};
模板bool VarData::IsTypeOf(int index)const
{
返回false;
}
模板bool VarData::IsTypeOf(int index)const
{
返回false;
}

非常感谢,查尔斯和纳瓦兹!我不认为VarData::IsTypeOf声明会起作用……我应该补充一点,为函数添加内联关键字是非常重要的,这些函数在类范围之外声明,至少如果在头文件中定义了模板类函数。否则链接器将无法工作…@Ryan sd您的意思是应该编写正确的专门化
模板内联bool VarData::IsTypeOf(int index)const{return false;}
模板内联bool VarData::IsTypeOf(int index)const{return false;}
?在没有内联的情况下,我很奇怪地遇到了同样的问题。我仍然会遇到编译错误,但内联的编译很好@Ryan。谢谢你的提示。可能是重复的