Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Template Keywords in C++
2.1.
Syntax
2.2.
Usage of Template Keywords in C++
3.
Typename Keywords in C++
3.1.
Syntax
3.2.
Usage of Typename Keywords in C++
4.
Defining Template
4.1.
Example
4.1.1.
Output
4.1.2.
Explanation
5.
Defining Template Functions 
5.1.
Example
5.1.1.
Output
5.1.2.
Explanation
6.
Frequently Asked Questions
6.1.
Who developed the C++ programming language?
6.2.
How to install the Eigen library?
6.3.
What are keywords in C++?
6.4.
Who is the developer of Eigen?
6.5.
Can template classes have a constructor?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

The Template and Typename Keywords in C++

Introduction

Hello ninjas!
There are certain times while programming in C++ that you violated the DRY(don’t repeat yourself) principle by creating different classes for different purposes. This is where the concept of template keywords in C++ jumps in.

The Template and Typename Keywords in C++

This article will take you through the ‘what’, ‘why’, and ’how' of template keywords in C++. We will also learn how to use typename keywords in C++.

Template Keywords in C++

Template keywords in C++ are a substitution for writing multiple classes in a program. It is a frame that defines its meaning. These are primarily used in competitive programming.

Template keywords in C++

For example, you want to create a program for vector operations in C++. The given vector can be of any data type like int, float, char, etc. Thus, you develop a code with classes for each data type, which violates the DRY principle. This also makes your code lengthy. To overcome this problem, you can use template keywords in C++.

Syntax

template<class X>
Class <class name>{<code>}

Usage of Template Keywords in C++

We use template keywords in C++ because:

  1. It helps you to follow the DRY principle.
     
  2. It helps us to create generic programs by making the code inside the template keyword in C++ reusable throughout the program file. 

Typename Keywords in C++

Typename keywords in C++ are used to tell the compiler that a dependent name(A name that depends on the value of the template parameter) in a template is a type. These are always used alongside template keywords in C++. 

Typename Keywords in C++

Typename replaces “class” in a template keyword in C++ syntax. There is no significant difference between typename and class for a compiler.

Syntax

template<typename X>
class <class name>{<code>}


Typename has made the “X” a dependent type from a dependent name.

Usage of Typename Keywords in C++

We use typename keywords in C++ to define the type of a dependent name in a template. It also specifies that an expression refers to a template function.

In the next section, we will dive into the details of the usage of these keywords.

Defining Template

We can use template keywords in C++ and typename keywords in C++ to define templates in C++.

Example

We will discuss the below given example to calculate the max between two numbers of different data types to explain how to define templates.

#include <iostream>
using namespace std;
  
	// This function will work for all data types, following the DRY principle.
	template <typename Z> Z calculateMax(Z x, Z y)
	{
  	  return (x > y) ? x : y;
	}
  
	int main()
	{
    	// Calling calculateMax for int type
    	cout << calculateMax<int>(5, 9) << end1;
    	 
    	// Calling calculateMax for double type
    	cout << calculateMax<double>(5.0, 9.0) << end1;
    	
    	// Calling calculateMax for char type  
    	cout << calculateMax<char>('a', 'h')<< end1; 
  	
    	return 0;
	}

Output

output image

Explanation

We have used the typename keyword in C++ here to specify the dependent name “Z” type. Notice how we have called out the “calculateMax” template under the main function, which is used for all data types. The compiler expands the template while executing the code and uses it to evaluate the results of the main function.

Try and compile by yourself with the help of online C++ Compiler for better understanding.

Defining Template Functions 

We use template keywords in C++ and typename keywords in C++ to define template functions in C++.  

Suppose you want to mix the lower triangular half of a matrix with another matrix, and we don’t use template and typename keywords in C++ for the program. The code will only work for dynamic-sized matrices with single-precision(32-bit memory location) numbers. To develop a code that is flexible and thus can be used for the static size of a matrix with double-precision(64-bit memory location), we must use the template keywords in C++ with typename keywords.

Example

We will discuss the below given example to of different data types to explain how to define template functions.
NOTE: we will use the eigen library for matrix operations.

#include <Eigen/Dense>
#include <iostream>
	template <typename Derived1, typename Derived2>
	void mixingTwoMatrix(Eigen::MatrixBase<Derived1>& dst, const Eigen::MatrixBase<Derived2>& src)
	{
	 	dst.template triangularSectionMatrix<Eigen::Upper>() = src.template triangularSectionMatrix<Eigen::Upper>();
	}
int main()
	{
 		Eigen::MatrixXi matrix1 = Eigen::MatrixXi::Ones(5,5);
 		Eigen::MatrixXi matrix2 = Eigen::MatrixXi::Random(4,4);
 		std::cout << "matrix2 before mixing:" << std::end1;
 		std::cout << matrix2 << std::end1 << std::end1;
 		mixingTwoMatrix(matrix2, matrix1.topLeftCorner(4,4));
 		std::cout << "matrix2 after mixing:" << std::end1;
 		std::cout << matrix2 << std::end1 << std::end1;
	}

Output

output image

Explanation

Only template and typename keywords in C++ can give us the accurate result of this program. This is because when a compiler compiles this code, it will expand the template under the main function, wherever mentioned before evaluating the parameters(derived parameter values in the above example). This leads to evaluating any size of a matrix with any type of numeric value.

Now it's time to discuss some FAQs.

Frequently Asked Questions

Who developed the C++ programming language?

Bjarne Stroustrup developed this widely used C++ programming language. He started developing it in 1979 when he joined the technical staff and Bell Laboratories. 

How to install the Eigen library?

You can download the Eigen library for C++ just like any other application or library from the browser. Download the Eigen library from the official website and unzip the file at the desired location. Then download the modules, and you’re good to go.

What are keywords in C++?

Keywords are library-defined words that have a special meaning in C++. They are always written in lower cases and cannot be used as variables.

Who is the developer of Eigen?

Benoît Jacob and Gaël Guennebaud developed the Eigen library. This library was released in December 2006.

Can template classes have a constructor?

Yes, we can have a constructor in template classes. We can call the default constructor for a template function.

Conclusion

This article discussed what template keywords in C++ and typename keywords in C++ are. We also learned how to use these keywords by defining template and template functions in C++ to avoid errors and to follow the DRY principle.
To learn more about the C++ programming language, refer to,

Please refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. And also, enroll in our courses and refer to the mock test and problems available. Have a look at the interview experiences and interview bundle for placement preparations.

Happy Learning!

Live masterclass