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

use*_*165 6 c++ templates template-specialization

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

我在里面写了这段代码:

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

我想添加另一种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.
   }
};
Run Code Online (Sandbox Code Playgroud)
  • 为什么我会收到此语法的错误("在'''令牌之前预期的unqualified-id")?
  • 为什么这不可能?
  • 如何在不声明新专业类的情况下解决这个问题?

谢谢

T.C*_*.C. 11

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.
}
Run Code Online (Sandbox Code Playgroud)