C++ Template Function | How to Write a Template Function C++?

What is a Template Function in C++?

In C++, a template is a simple but powerful tool.

The simple idea is to pass the data type as a parameter so that we don’t need to write the same code for different data types.

C++ adds two new keywords to support templates: template‘ and typename. Then “class” can always be used in place of the second keyword.

For example, a company that makes software might need to sort() for different data types.

We don’t have to write and keep track of multiple codes if we write one sort() function and pass the data type as a parameter.

What is the Difference Between Class Template and Function Template in C++?

Function templates can be used as generic types, which are special functions.

Further function templates can be used for more than one data type or class without having to write the same code over again.

Class templates are like function templates, but they can be used when a class defines something that doesn’t depend on the data type.

It is helpful for classes like LinkedList, BinaryTree, Stack, Queue, Array, etc.

How many types of Templates are there in C++?

In the C++ programming language, there are two main types of templates.

  • Function Templates
  • Class Templates
C++ TEMPLATES
C++ TEMPLATES

What are the Advantages of using Templates in C++?

C++ templates allow you to create a group of functions or classes that may act on various data types.

  • You can also make a set of typesafe classes with the help of class templates.

  • Templates are sometimes preferable to C macros and void pointers, and they are convenient when dealing with collections and smart pointers (from MSDN).

  • Some things seem easy to do with templates, like the equality operator, which is very hard to do with traditional OO techniques like polymorphism. OOP polymorphism includes function overloading and templates.

  • Parameters are known at compiler time; therefore, template classes are safer than code structures that are resolved at run time, like abstract classes.

  • Most of the time, the main reason to use templates with STL is that it can cut a lot of development time.

What are the Disadvantages of Templates in C++?

  • Some older compilers didn’t handle templates well. Templates may make code harder to transfer.

  • When a template definition error is found, many compilers don’t have clear instructions for what to do. This can make it harder to make templates.

  • Since the compiler makes more code for each template type, using templates without thinking about it can lead to code bloat, which makes executables bigger.

  • Because a template demonstrates how it works, building huge systems incorrectly may take longer.

  • Template-based programming is hard to debug.

  • Headers have templates, the whole project must be rebuilt from scratch when changes are made.

  • No information is hiding. All code is exposed in the header file. No one library can solely contain the code

  • Template libraries are header-only; library code is built alongside user code. This simplifies library installation and use.

What is the Need of Class Template in C++?

C++ uses templates to make generics work. You may give data type as a parameter to avoid writing the same code for various data types.

  • Remove code duplication
  • Generic callback
  • Re-use source code as opposed to inheritance and composition, which provides a way to reuse object code
CLASS TEMPLATE
CLASS TEMPLATE

C++ Function Templates

Function templates are specialized function works and are compatible with generic types. We create a function that can be applied to various data types.

For example: sort(), maximum(), minimal(), and printArray are examples of function templates().

A function template starts with the keyword”template“which is followed by the template parameter(s) inside <> and then the function definition.

The general syntax for function template:

template <typename T>
T functionName(T parameter1, T parameter2, ...) {
    // code
}

Example:

#include <iostream>
using namespace std;
  
template <typename T> T myMax(T x, T y)
{
    return (x > y) ? x : y;
}
  
int main()
{
    cout << myMax<int>(3, 7) << endl; 
    cout << myMax<double>(3.0, 7.0)
         << endl; 
    cout << myMax<char>('g', 'e')
         << endl; 
  
    return 0;
}

Output:

7
7
g

How to Call a Template Function C++?

Once we’ve declared and defined a function template, we can use the following syntax to call it from other functions or templates, like the main() function.

functionName<dataType>(parameter1, parameter2,...);

Example:

#include <iostream>
using namespace std;

template <typename T>
T add(T num1, T num2) {
    return (num1 + num2);
}

int main() {
    int result1;
    double result2;
    result1 = add<int>(2, 3);
    cout << "2 + 3 = " << result1 << endl;

    result2 = add<double>(2.2, 3.3);
    cout << "2.2 + 3.3 = " << result2 << endl;

    return 0;
}

Output:

2 + 3 = 5
2.2 + 3.3 = 5.5

Here, we create a template that adds two numbers. Then the main() function called to add int and double numbers.

C++ Class Templates

Class Templates like function templates and class templates are useful when a class defines something that is independent of the data type.

A class template starts with the keyword template followed by template parameter(s) inside <> , which is followed by the class declaration.

Example:

Following is a simple example of a template Array class.

#include <iostream>
using namespace std;

template <class T>
class Number {
   private:
      T num;

   public:
    Number(T n) : num(n) {} 
    T getNum() {
        return num;
    }
};

int main() {
    Number<int> numberInt(7);
    Number<double> numberDouble(7.7);

    cout << "int Number = " << numberInt.getNum() << endl;
    cout << "double Number = " << numberDouble.getNum() << endl;

    return 0;
}

Output:

int Number = 7
double Number = 7.7

In this program, we’ve made a class template “Number” by putting the code into it.

Notice that the variable num, the constructor argument n, and the function getNum() are of type T, or have a return type T.

That means that they can be of any type.

In main(), we have implemented the class template by creating its objects. Notice the codes Number<int> and Number<double> in the code above.

This makes a class definition for both the int and double variables.

C++ Template Specialization

C++ Template Specialization can declare if we want to give it a different implementation when a certain type is passed as a template parameter.

The syntax used in the class template specialization:

template <> class mycontainer <char> { ... };

Example:

#include <iostream>
using namespace std;

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

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 (7);
  mycontainer<char> mychar ('j');
  cout << myint.increase() << endl;
  cout << mychar.uppercase() << endl;
  return 0;
}

Output:

8
J

First, note the empty template <> parameter list before the class template name.

This is to declare it as a template specialization explicitly.

But more important than this prefix is the <char> specialization parameter after the class template name.

This specialization parameter itself tells us the type for which a template class specialization is going to be declared (char).

Notice how the generic class template is different from the specialization:

template <class T> class mycontainer { ... }; template <> class mycontainer <char> { ... };

The first line represents the general template, whereas the second line represents the specialization.

When declaring specializations for a template class, we must also specify all of its members, even those that are identical to the generic template class, since there is no “inheritance” of members from the general template to the specialization.

Can we Provide Templates with Non-type Parameters?

A template non-type parameter is a template parameter where the type is already set, and a constexpr value is passed in as a template argument and used instead.

A non-type parameter can be any of the following types:

  • An integral type
  • An enumeration type
  • A pointer or reference to a class object
  • A pointer or reference to a function
  • A pointer or reference to a class member function
  • std::nullptr_t
  • A floating point type (since C++20)

Summary

The templates feature in programming is a key part of making a program run quickly and takes up little space in memory because code can be reused.

You can easily overload template functions because you can define a group of classes and functions to handle different types of data.

That’s it! The C++ Template Function is now complete!

This is very important to our understanding of the C++ Programming language.

Leave a Comment