user2630165
user2630165

Reputation: 311

template class with a single method specialized in C++

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

Thanks

Upvotes: 7

Views: 2397

Answers (2)

T.C.
T.C.

Reputation: 137310

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

Upvotes: 12

Adam
Adam

Reputation: 851

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

Upvotes: 0

Related Questions