TEMPLATE IN C++ Function Templates

Similar documents
Inheritance and Overloading. Week 11

More Functions. Pass by Value. Example: Exchange two numbers. Storage Classes. Passing Parameters by Reference. Pass by value and by reference

4. C++ functions. 1. Library Function 2. User-defined Function

A First Program - Greeting.cpp

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

Function Overloading

Object Oriented Design

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

Exception with arguments

CS 247: Software Engineering Principles. ADT Design

CS2141 Software Development using C/C++ C++ Basics

Data Structures using OOP C++ Lecture 3

Lab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1

Programming in C++: Assignment Week 8

What we will learn about this week: Declaring and referencing arrays. arrays as function arguments. Arrays

Introduction to Programming

Fundamentals of Programming. Lecture 19 Hamed Rasifard

Lab Instructor : Jean Lai

Homework #3 CS2255 Fall 2012

Constructor - example

Lecture 23: Pointer Arithmetic

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

CHAPTER 4 FUNCTIONS. 4.1 Introduction

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Data type of a pointer must be same as the data type of the variable to which the pointer variable is pointing. Here are a few examples:

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

Functions. A function is a subprogram that performs a specific task. Functions you know: cout << Hi ; cin >> number;

C++ Programming for Non-C Programmers. Supplement

Chapter 16. Templates. Copyright 2010 Pearson Addison-Wesley. All rights reserved

W3101: Programming Languages C++ Ramana Isukapalli

Dr. Md. Humayun Kabir CSE Department, BUET

Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Implementing an ADT with a Class

C++ Programming for Non-C Programmers. Supplement

Object Oriented Design

Developed By : Mrs. K. M. Sanghavi

Object-Oriented Programming (OOP) Fundamental Principles of OOP

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A.

EECS402 Lecture 02. Functions. Function Prototype

Recharge (int, int, int); //constructor declared void disply();

(6) The specification of a name with its type in a program. (7) Some memory that holds a value of a given type.

Exam 3 Chapters 7 & 9

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

Functions and Recursion

VARIABLES & ASSIGNMENTS

Exercise 1.1 Hello world

C++ Programming Fundamentals

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

Object Oriented Programming Using C++ Mathematics & Computing IET, Katunayake

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018


1 Unit 8 'for' Loops

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Introduction to C++ Systems Programming

Review of Important Topics in CS1600. Functions Arrays C-strings

Module Operator Overloading and Type Conversion. Table of Contents

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

Lecture-5. Miscellaneous topics Templates. W3101: Programming Languages C++ Ramana Isukapalli

Chapter 1 INTRODUCTION

C++ For Science and Engineering Lecture 15

The University Of Michigan. EECS402 Lecture 02. Andrew M. Morgan. Savitch Ch. 3-4 Functions Value and Reference Parameters.

Semantics of C++ Hauptseminar im Wintersemester 2009/10 Templates

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Agenda / Learning Objectives: 1. Map out a plan to study for mid-term Review the C++ operators up to logical operators. 3. Read about the tips

(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University

Review: C++ Basic Concepts. Dr. Yingwu Zhu

2 2

Intermediate Programming, Spring 2017*

This chapter introduces the notion of namespace. We also describe how to manage input and output with C++ commands via the terminal or files.

Introduction to Programming using C++

CSCE Practice Midterm. Data Types

CMSC202 Computer Science II for Majors

COEN244: Class & function templates

1. (25 pts) Short Answer. Provide brief (1-3 sentence) answers to the following:

Lab 1: First Steps in C++ - Eclipse

Template. SSE2034: System Software Experiment 3, Fall 2018, Jinkyu Jeong

The American University in Cairo Department of Computer Science & Engineeringt CSCI &09 Dr. KHALIL Exam-I Fall 2009

Computer Programming

AN OVERVIEW OF C++ 1

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

Programming Fundamentals. With C++ Variable Declaration, Evaluation and Assignment 1

Chapter 1 Introduction to Computers and C++ Programming

(3) Some memory that holds a value of a given type. (8) The basic unit of addressing in most computers.

Generic Programming: Overloading and Templates

Reference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that

Chapter-11 POINTERS. Important 3 Marks. Introduction: Memory Utilization of Pointer: Pointer:

Homework 5. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

CS242 COMPUTER PROGRAMMING

Lecture on pointers, references, and arrays and vectors

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

Fast Introduction to Object Oriented Programming and C++

Transcription:

TEMPLATE IN C++ Templates are powerful features of C++ which allows you to write generic programs. In simple terms, you can create a single function or a class to work with different data types using templates. Templates are often used in larger codebase for the purpose of code reusability and flexibility of the programs. The concept of templates can be used in two different ways: Function Templates Class Templates Function Templates A function template works in a similar to a normal function, with one key difference. A single function template can work with different data types at once but, a single normal function can only work with one set of data types. Normally, if you need to perform identical operations on two or more types of data, you use function overloading to create two functions with the required function declaration. However, a better approach would be to use function templates because you can perform the same task writing less and maintainable code. How to declare a function template? A function template starts with the keyword template followed by template parameter/s inside < > which is followed by function declaration. T somefunction(t arg)........ In the above code, T is a template argument that accepts different data types (int, float), and class is a keyword. You can also use keyword typename instead of class in the above example. When, an argument of a data type is passed to somefunction( ), compiler generates a new version of somefunction() for the given data type. Example 1: Function Template to find the largest number #include <iostream> using namespace std; // template function T Large(T n1, T n2) Ashish Prajapati Page 1

return (n1 > n2)? n1 : n2; int main() int i1, i2; float f1, f2; char c1, c2; cout << "Enter two integers:\n"; cin >> i1 >> i2; cout << Large(i1, i2) <<" is larger." << endl; cout << "\nenter two floating-point numbers:\n"; cin >> f1 >> f2; cout << Large(f1, f2) <<" is larger." << endl; cout << "\nenter two characters:\n"; cin >> c1 >> c2; cout << Large(c1, c2) << " has larger ASCII value."; return 0; Output Enter two integers: 5 10 10 is larger. Enter two floating-point numbers: 12.4 10.2 12.4 is larger. Enter two characters: z Z z has larger ASCII value. In the above program, a function template Large() is defined that accepts two arguments n1 and n2 of data type T. T signifies that argument can be of any data type. Large() function returns the largest among the two arguments using a simple conditional operation. Inside the main() function, variables of three different data types: int, float and charare declared. The variables are then passed to the Large() function template as normal functions. During run-time, when an integer is passed to the template function, compiler knows it has to generate a Large() function to accept the int arguments and does so. Ashish Prajapati Page 2

Similarly, when floating-point data and char data are passed, it knows the argument data types and generates the Large() function accordingly. This way, using only a single function template replaced three identical normal functions and made your code maintainable. Example 2: Swap Data Using Function Templates #include <iostream> using namespace std; template <typename T> void Swap(T &n1, T &n2) T temp; temp = n1; n1 = n2; n2 = temp; int main() int i1 = 1, i2 = 2; float f1 = 1.1, f2 = 2.2; char c1 = 'a', c2 = 'b'; cout << "Before passing data to function template.\n"; cout << "i1 = " << i1 << "\ni2 = " << i2; cout << "\nf1 = " << f1 << "\nf2 = " << f2; cout << "\nc1 = " << c1 << "\nc2 = " << c2; Swap(i1, i2); Swap(f1, f2); Swap(c1, c2); cout << "\n\nafter passing data to function template.\n"; cout << "i1 = " << i1 << "\ni2 = " << i2; cout << "\nf1 = " << f1 << "\nf2 = " << f2; cout << "\nc1 = " << c1 << "\nc2 = " << c2; return 0; Output Before passing data to function template. i1 = 1 i2 = 2 f1 = 1.1 f2 = 2.2 c1 = a c2 = b Ashish Prajapati Page 3

After passing data to function template. i1 = 2 i2 = 1 f1 = 2.2 f2 = 1.1 c1 = b c2 = a In this program, instead of calling a function by passing a value, a call by reference is issued. The Swap() function template takes two arguments and swaps them by reference. Class Templates Like function templates, you can also create class templates for generic class operations. Sometimes, you need a class implementation that is same for all classes, only the data types used are different. Normally, you would need to create a different class for each data type OR create different member variables and functions within a single class. This will unnecessarily bloat your code base and will be hard to maintain, as a change is one class/function should be performed on all classes/functions. However, class templates make it easy to reuse the same code for all data types. How to declare a class template? class classname........ public: T var; T someoperation(t arg);........ ; In the above declaration, T is the template argument which is a placeholder for the data type used. Inside the class body, a member variable var and a member function someoperation() are both of type T. How to create a class template object? To create a class template object, you need to define the data type inside a < > when creation. classname<datatype> classobject; For example: classname<int> classobject; classname<float> classobject; classname<string> classobject; Ashish Prajapati Page 4

Example 3: Simple calculator using Class template Program to add, subtract, multiply and divide two numbers using class template #include <iostream> using namespace std; class Calculator private: T num1, num2; public: endl; Calculator(T n1, T n2) num1 = n1; num2 = n2; void displayresult() cout << "Numbers are: " << num1 << " and " << num2 << "." << cout << "Addition is: " << add() << endl; cout << "Subtraction is: " << subtract() << endl; cout << "Product is: " << multiply() << endl; cout << "Division is: " << divide() << endl; T add() return num1 + num2; T subtract() return num1 - num2; T multiply() return num1 * num2; ; T divide() return num1 / num2; int main() Calculator<int> intcalc(2, 1); Calculator<float> floatcalc(2.4, 1.2); cout << "Int results:" << endl; intcalc.displayresult(); cout << endl << "Float results:" << endl; floatcalc.displayresult(); return 0; Ashish Prajapati Page 5

Output Int results: Numbers are: 2 and 1. Addition is: 3a Subtraction is: 1 Product is: 2 Division is: 2 Float results: Numbers are: 2.4 and 1.2. Addition is: 3.6 Subtraction is: 1.2 Product is: 2.88 Division is: 2 In the above program, a class template Calculator is declared. The class contains two private members of type T: num1 & num2, and a constructor to initalize the members. It also contains public member functions to calculate the addition, subtraction, multiplication and division of the numbers which return the value of data type defined by the user. Likewise, a function displayresult() to display the final output to the screen. In the main() function, two different Calculator objects intcalc and floatcalc are created for data types: int and float respectively. The values are initialized using the constructor. Notice we use <int> and <float> while creating the objects. These tell the compiler the data type used for the class creation. This creates a class definition each for int and float, which are then used accordingly. Then, displayresult() of both objects is called which performs the Calculator operations and displays the output. Ashish Prajapati Page 6