模板类,使用一种专门用于C ++的方法

时间:2014-09-08 12:32:37

标签: c++ templates template-specialization

我只有一个用于C ++学校作业的hpp文件(我不允许添加cpp文件,声明和实现都应该写在文件中)。

我在里面写了这段代码:

template<class T>
class Matrix
{
   void foo()
   {
       //do something for a T variable.
   }
};

我想添加另一个foo方法,但此foo()仅适用于<int>。 我在某些地方读过,我需要声明一个新的专业化类来实现它。但我想要的是专门的foo将位于原foo之下,所以它看起来像这样:

template<class T>
class Matrix
{
   void foo(T x)
   {
       //do something for a T variable.
   }
   template<> void foo<int>(int x)
   {
       //do something for an int variable.
   }
};
  • 为什么我的语法错误(&#34;在&#39;&lt;&#39;令牌&#34;之前预期的非合格ID)?
  • 为什么这不可能?
  • 如何在不声明新专业类的情况下解决此问题?

由于

2 个答案:

答案 0 :(得分:10)

foo不是模板。它是模板的成员函数。因此foo<int>毫无意义。 (此外,必须在命名空间范围内声明显式特化。)

您可以显式地专门化类模板的特定隐式实例化的成员函数:

template<class T>
class Matrix
{
   void foo(T x)
   {
       //do something for a T variable.
   }
};

// must mark this inline to avoid ODR violations
// when it's defined in a header
template<> inline void Matrix<int>::foo(int x)
{
     //do something for an int variable.
}

答案 1 :(得分:0)

您需要将原始foo方法定义为模板,实际上您的类不需要是模板,只需要方法:

class Matrix
{
    template<typename T> void foo(T x)
    {
        //do something for a T variable.
    }
    template<> void foo<int>(int x)
    {
        //do something for an int variable.
    }
};

更新:代码仅适用于Visual Studio。这是一个应该在其他地方运行的代码:

class Matrix
{
    template<typename T> void foo(T x)
    {
        //do something for a T variable.
    }
};

template<> void Matrix::foo<int>(int x)
{
    //do something for an int variable.
}
相关问题