Template Class Specialization

JAVA: You need more than two classes with different names.

interface ImplementsMe<T> {

  public void foo(T v);

}

class Master<T> implements ImplementsMe<T> {

  public void foo(T v) {
    
    System.out.println(“I’m master!”);
    System.out.println(v);
  }
}

class StringMaster implements ImplementsMe<String> {

  public void foo(String v) {
    
    System.out.println(“I’m string!”);
    System.out.println(v);
  }
}

public class TemplateTest {

  public static void main(String[] args) {

    ImplementsMe<Integer> i1 = new Master<Integer>();
    ImplementsMe<String> i2 = new StringSpecialized();

    i1.foo(1);
    i2.foo(“hi”);
  }
}

C++: Born to be able to specialize templates.

#include <iostream>

using namespace std;

template<typename T>
class ImplementsMe
{
public:
  virtual void foo(T v)=0;
  virtual ~ImplementsMe() {}
};

template<typename T>
class Master: public ImplementsMe<T>
{
public:
  virtual void foo(T v)
  {
    cout << “I’m master” << endl;
    cout << v << endl;
  }
};

template<>
class Master<string>: public ImplementsMe<string>
{
public:
  virtual void foo(string v)
  {
    cout << “I’m string” << endl;
    cout << v << endl;
  }
};

int main(void)
{

  ImplementsMe<int> *i1 = new Master<int>;
  ImplementsMe<string> *i2 = new Master<string>;

  i1>foo(1);
  i2>foo(“hi”);

  return EXIT_SUCCESS;
}

In JAVA, there is exactly one Class instance for each class whether the class is a template or not. And that makes template specialization almost impossible.

Hence, to specialize the behavior of a certain template, you must implement a factory class because you may want to hide implementation details (say, StringMaster) from clients.

To my best knowledge, there is no elegance solution than to “factory and specialized class of diffrent class name” approach.

p.s. I know that I’ve forgot to delete i1 and i2 in C++ code.

Similar Posts:

Post a Comment

Your email is never published nor shared.