【问题标题】:GCC error: explicit specialization in non-namespace scopeGCC 错误:非命名空间范围内的显式特化
【发布时间】:2011-08-12 05:51:51
【问题描述】:

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

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

【问题讨论】:

标签: c++ templates gcc


【解决方案1】:

您只需将成员模板的特化移到类主体之外。

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

【讨论】:

  • 非常感谢,查尔斯和纳瓦兹!我不认为 VarData::IsTypeOf 声明会起作用...
  • 我应该补充一点,为在类范围之外声明的函数添加 inline 关键字非常重要,至少如果模板类函数在头文件中定义。否则链接器将无法工作...
  • @Ryan sd 你的意思是正确的专业化应该写成template &lt;&gt; inline bool VarData::IsTypeOf &lt; int &gt; (int index) const{return false;}template &lt;&gt; inline bool VarData::IsTypeOf &lt; double &gt; (int index) const{return false;}
  • 我在没有内联的情况下奇怪地面临同样的问题我仍然得到编译错误但内联它的编译很好@Ryan。感谢您的提示。
【解决方案2】:

将类外的特化定义为:

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

【讨论】:

    猜你喜欢
    • 2018-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    相关资源
    最近更新 更多