0

I have observed that whenever a template class is specialized (partially/completely), all the member functions needs to be explicitly defined otherwise there is an error. Here is an example below

#include <iostream>

template<typename T, typename U> //Primary
struct test
{
   void f() { std::cout << "\nPrimary"; }
   void g() { std::cout << "Called g()\n";}
};

template <typename T> //Specialization
struct test<T, int*>
{
   void f() { std::cout << "\nPartial Specialization"; }
};


template<> //Full specialization
struct test<int*, int*>
{
   void f() { std::cout << "\nFull Specialization\n"; }
};

int main()
{
    test<int, double> t1;
    t1.f();
    t1.g();

    test<double, int*> t2;
    t2.f();
    t2.g();

    test<int*, int*> t3;
    t3.f();
    t3.g();
}

Here t2.g() and t3.g() gives compile time error as they are not explicitly defined. If for every specialization, the member functions needs to be defined again. What's the advantage of allow partial/fully specialization?

Rachit Agrawal
  • 3,203
  • 10
  • 32
  • 56
  • For structures the use-cases are pretty limited (due to the limitation that all functions in the structure needs to be reimplemented), but it's not *zero*. There might be use-cases where it makes sense to do partial specialization even if one need to reimplement the functions. – Some programmer dude Feb 10 '20 at 12:39
  • 1
    Class specialization is not at equivalent to inheritance! The specialized class is a completely different class – theWiseBro Feb 10 '20 at 12:50
  • Does this answer your question? [Partial specialization of a method in a templated class](https://stackoverflow.com/questions/10284498/partial-specialization-of-a-method-in-a-templated-class) – Marek R Feb 10 '20 at 12:52

2 Answers2

1

I think you've got the concept of class specializations wrong here. Class specialization is not inheritance. The specialized class is a different class than the initial one. Nothing is shared between the two. And hence, there doesn't exist any g() method in the specialized ones.

If you're looking for a way to just have the methods different, you should look into method specializations instead.

theWiseBro
  • 1,439
  • 12
  • 11
0

I think the main purpose for specialization is defining "exceptions" if you want to handle some data types in different ways.

Looking at partial specialization consider the following:

// NOT specialized
template <typename T>
struct test <T, T>
{
   ...
};

// partially specialized
template <typename T>
struct test <T*, T*>
{
  ...
}; 

The latter example is already partially specialized because you are telling the compiler to expect any type of pointer. And this can be useful of course because you might want to handle pointer-types slightly different to non-pointer types (checking for being NULL for example)

I recommend reading this article

Odysseus
  • 1,213
  • 4
  • 12