Q:

C++ Program to demonstrate an Example of Template specialization

belongs to collection: C++ Template Solved Programs

0

Write a C++ Program to demonstrate an Example of Template specialization. Here’s a Simple C++ Program to demonstrate an Example of Template specialization in C++ Programming Language.


What are Templates in C++ ?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type.

 
 

A template is a blueprint or formula for creating a generic class or a function. The library containers like iterators and algorithms are examples of generic programming and have been developed using template concept.

There is a single definition of each container, such as vector, but we can define many different kinds of vectors for example, vector <int> or vector <string>..


Function Template :

The general form of a template function definition is shown here:

 

template <class type> ret-type func-name(parameter list)

{
// body of function
}


Class Template :

Just as we can define function templates, we can also define class templates. The general form of a generic class declaration is shown here:

template <class type> class class-name

{
.
.
.
}


Below is the source code for C++ Program to demonstrate an Example of Template specialization which is successfully compiled and run on Windows System to produce desired output as shown below :


SOURCE CODE : :

/* C++ Program to demonstrate an Example of Template specialization  */

#include <iostream>
using namespace std;

// class template:
template <class T>
class mycontainer {
    T element;
  public:
    mycontainer (T arg) {element=arg;}
    T increase () {return ++element;}
};

// class template specialization:
template <>
class mycontainer <char> {
    char element;
  public:
    mycontainer (char arg) {element=arg;}
    char uppercase ()
    {
      if ((element>='a')&&(element<='z'))
      element+='A'-'a';
      return element;
    }
};

int main () {
  mycontainer<int> myint (12);
  mycontainer<char> mychar ('c');
  cout << myint.increase() << endl;
  cout << mychar.uppercase() << endl;
  return 0;
}

OUTPUT : :


/* C++ Program to demonstrate an Example of Template specialization */

13
C
 
Exit code: 0 (normal program termination)

Above is the source code and output for C++ Program to demonstrate an Example of Template specialization which is successfully compiled and run on Windows System to produce desired output.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ Program to demonstrate an Example of Non-type ... >>
<< C++ Program to build Simple calculator using Class...