Template specialization of a single method from a templated class

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Gobi Sakthivel
    New Member
    • Jan 2013
    • 26

    Template specialization of a single method from a templated class

    I want to specialize a particular function for Integer datatype inside a class template. My XX.h will be
    Code:
    namespace ZZ
    {
           template <class T>
           class XX
           {
               void doSomething(T x);
           };
    }
    Can someone provide me XX.cpp which has template specialization for the function doSomething on Integer datatype.

    I tried the following in XX.cpp
    Code:
    #include "XX.h"
    using namespace ZZ;
    
    template <class T>
    void XX<T>::doSomething(T x)
    {
     // Do somtehing with a generic T
    }
    
    template <>
    void XX<int>::doSomething(int v)
    {
     // Do somtehing with int
    }
    But this code is not working, can someone help me.
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Here you go.

    This should be in your header file:

    Code:
    namespace ZZ
    {
           template <class T>
           class XX
           {
               void doSomething(T x);
           };
    }
    template <> void ZZ::XX<int>::doSomething(int x);
    I added the explicit specialization for the int data type. This tells the compiler to not use the template with int because you have already written that function.

    Here is your .cpp:

    Code:
    template <class T>
    void ZZ:: XX<T>::doSomething(T x)
    {
     // Do somtehing with a generic T
    }
    
    
    void ZZ:: XX<int>::doSomething(int v)
    {
     // Do somtehing with int
    }
    I had to add that these functions are in the ZZ namespace.

    Comment

    • Gobi Sakthivel
      New Member
      • Jan 2013
      • 26

      #3
      Many Many Thanks dude...:)

      Comment

      Working...