template class with a single method specialized in C++

╄→гoц情女王★ 提交于 2020-12-05 07:11:59

问题


I only have an hpp file for a school assignment in C++ (I am not allowed to add a cpp file, declaration and implementation should be both written in the file).

I wrote this code inside it:

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

I would like to add another foo method, but this foo() will be specialized for only an <int>. I have read in some places that I need to declare a new specialization class for this to work. But what I want is that the specialized foo will lie just beneath the original foo, so it will look like this:

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.
   }
};
  • Why am I getting an error for this syntax ("expected unqualified-id before '<' token")?
  • Why isn't this possible?
  • How can I fix this without declaring a new specialized class?

Thanks


回答1:


foo isn't a template. It's a member function of a template. Thus foo<int> is meaningless. (Also, explicit specializations must be declared at namespace scope.)

You can explicitly specialize a member function of a particular implicit instantiation of a class template:

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



回答2:


You need to define the original foo method as a template, and actually there is no need for your class to be a template, only the method:

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

UPDATE: The code works only in Visual Studio. Here is a code that should work elsewhere too:

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


来源:https://stackoverflow.com/questions/25724360/template-class-with-a-single-method-specialized-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!