C++ Programming: chapter 8 – Templates

Slides:



Advertisements
Similar presentations
Lecture Computer Science I - Martin Hardwick Strings #include using namespace std; int main () { string word; cout
Advertisements

Vectors, lists and queues
Chapter 6 Advanced Function Features Pass by Value Pass by Reference Const parameters Overloaded functions.
Template Implicit function overload. Function overload Function overload double ssqq(double & a, double & b) { return(a*b);} float ssqq(float & a, float.
Templated Functions. Overloading vs Templating  Overloaded functions allow multiple functions with the same name.
1 Class Vehicle #include #define N 10../.. 2 Class Vehicle class vehicle { public: float speed; char colour[N+1]; char make[N+1];
Templates & Generic Programming Junaed Sattar November 12, 2008 Lecture 10.
 Review structures  Program to demonstrate a structure containing a pointer.
M. Taimoor Khan #include void main() { //This is my first C++ Program /* This program will display a string message on.
C++ function call by value The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter.
Functions Pass by Reference Alina Solovyova-Vincent Department of Computer Science & Engineering University of Nevada, Reno Fall 2005.
Searching and Sorting, Template Functions, and Vectors ITK 169 Fall 2003.
Templates © Bruce M. Reynolds & Cliff Green 1 // min function template #include using std::cout; using std::endl; // there’s already one of these in the.
Exception Handling. C++ 2 Outline  Throwing and handling exceptions  Exceptions of different types  The new operator and the exceptions  Re-throwing.
Method overloading contd class OverloadDemo { public static void main(String args[]) { Overload ob = new Overload(); int resI; double resD; // call all.
C++ Programming: chapter 4 – operator overloading 2014, Spring Pusan National University Ki-Joune Li 1.
1 Compiler directive: #define, usage 1 #include using namespace std; #define TAX //double TAX=0.08; #define LAST_NAME "Li" #define FIRST_NAME "Dennis"
Current Assignments Project 3 has been posted, due next Tuesday. Write a contact manager. Homework 6 will be posted this afternoon and will be due Friday.
第三章細部檢視類別 3-1 指定物件 3-2 傳遞物件給函數 3-3 從函數中傳回物件 3-4 簡介夥伴函數.
Chapter 2 Objects and Classes
“Generic Programming” ECE 297
Chapter 22 - C++ Templates
Introducing Templates and Generics in C++
#define #include<iostream> using namespace std; #define GO
Template Classes and Functions
Lecture 7-2 : STL Iterators
Two Dimensional Array Mr. Jacobs.
Command Line Arguments
Chapter 5 Function Basics
School of EECS, Peking University
Templates in C++.
Reserved Words.
Andy Wang Object Oriented Programming in C++ COP 3330
LEC Default Function Arguments, Ambiguity in Function Overloading and Operator Overloading.
Dynamic Memory Allocation Reference Variables
Lecture 7-2 : STL Iterators
Programming -2 برمجة -2 المحاضرة-5 Lecture-5.
CS 1430: Programming in C++ Turn in your Quiz1-2 No time to cover HiC.
Random Number Generation
פונקציות לעיתים קרובות לא נוח להגדיר את כל התוכנה בתוך גוף אחד.
C++ fundamentals Lecture 1, Chapter 2 – pp /22/2018 Y K Choi.
Name: Rubaisha Rajpoot
Creation and Use of Namespaces
Templaets It is a new concept which enables us to define “generic class “ and “generic function” to provide the “ generic programming” We are familiar.
Arrays November 8, 2017.
מחרוזות-String בשפת C++ ישנו תפקיד מיוחד למערך מסוג char רצף של תווים הנמצאים במערך מסוג char המסתיימת בתו אפס (הכוונה לאפס ממש '0\' , ולא לתו '0')
Introduction to Programming
Starting Out with C++: From Control Structures through Objects
Pointers & Functions.
Anatomy of a Function Part 1
C++ Programming: chapter 4 – operator overloading
Object-Oriented Programming (OOP) Lecture No. 37
Lecture 8-2 : STL Iterators and Algorithms
Introduction to Programming
CHAPTER 2 Arrays and Vectors.
foo.h #ifndef _FOO #define _FOO template <class T> class foo{
CHAPTER 2 Arrays and Vectors.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
STL (Standard Template Library)
Pointers & Functions.
CMSC 202 Lesson 6 Functions II.
CS 144 Advanced C++ Programming February 12 Class Meeting
Object-Oriented Programming (OOP) Lecture No. 34
C++ Programming: chapter 10 – STL
Anatomy of a Function Part 1
Chapter 22 - C++ Templates
Chapter 22 - C++ Templates
Programming Strings.
C++ Templates L04 - Iterator 10 – Iterator.
CSE Module 1 A Programming Primer
Presentation transcript:

C++ Programming: chapter 8 – Templates 2018, Spring Pusan National University Ki-Joune Li http://lik.pnu.kr

Function Template 바보 같은 중복 Template으로 중복 예방 T 가 int 로 간주 void swapValues(int& v1, int& v2) { int temp; temp=v1; v1=v2; v2=temp; } void swapValues(string& v1, string& v2) { float temp; temp=v1; v1=v2; v2=temp; } 바보 같은 중복 Template으로 중복 예방 template<class T> void swapValues(<T& v1, T& v2) { T temp; temp=v1; v1=v2; v2=temp; } int main(){ int a=1,b=2; swapValues<int>(a,b); // or swapValues(a,b); string c=“123”, d=“def”; swapValues<string>(c,d); // or swapValues(c,d); } T 가 int 로 간주 T 가 string 으로 간주

Function Template Template으로 중복 예방 모호할 경우에는 명시적으로 지정 int getMax(int, n, int* a) { int maxV=*a; for(int k=0;k<n;a++,k++) if(*a>maxV) maxV=*a; return MaxV } int getMax(int, n, float* a) { float maxV=*a; for(int k=0;k<n;a++,k++) if(*a>maxV) maxV=*a; return MaxV } Template으로 중복 예방 template<class T> T getMax(int, n, T* a) { T maxV=*a; for(int k=0;k<n;a++,k++) if(*a>maxV) maxV=*a; return MaxV } int x=getMax<int>(10, ages); float y=getMax<float>(50, scores); 모호할 경우에는 명시적으로 지정

Function Template – Function Overloading #include <iostream> using namespace std; template <class X> void f(X a) {   cout << "Inside f(X a)”<<a <<“\n"; } template <class X, class Y> void f(X a, Y b) {   cout << "Inside f(X a, Y b)” <<a <<“:”<< b<<“\n"; } int main() {   f(10);     // calls f(X)   f(10, 20); // calls f(X, Y)   return 0; }

Class Template Template으로 중복 예방 T를 int 로 간주 T를 float 으로 간주 PNU class IntVector { int* values; int num; public: IntVector(int); ~IntVector() { delete[] values;} int operator[](int i) { return values[i]; } }; IntVector::IntVector(int n): num(n) { values=new int[n];} class FloatVector { float* values; int num; public: FloatVector(int); ~FloatVector() { delete[] values;} float operator[](int i) { return values[i]; } }; FloatVector::FloatVector(int n): num(n) { values=new int[n]; } Template으로 중복 예방 T를 int 로 간주 int main() { Vector <int> iV(4);     int i;     for(i=0;i<4;i++) iV[i] = i*i;     for(i=0;i<4;i++) cout<<iV[i] << "  ";     cout << endl;     Vector <float> fV(4);     for(i=0;i<4;i++) fV[i] = sqrt(i);     for(i=0;i<4;i++) cout<<fV[i] << "  ";     return 0; } template<class T> class Array { int num; public: Vector(T); ~Vector() { delete[] values;} T& operator[](int i) { return values[i]; } }; Vector<T>::Vector(int n): num(n) { values=new int[n]; } T를 float 으로 간주 2

Class Template PNU #include <iostream> using namespace std;   template <class T> class MyClass {    T x;  public:    MyClass(T a) {       cout << "Inside generic MyClass\n";      x = a;    }    T getx() { return x; }  };  // Explicit specialization for int.  template <> class MyClass<int> {    int x;    MyClass(int a) {       cout << "Inside MyClass<int> specialization\n";      x = a * a;    int getx() { return x; }  int main()  {    MyClass<double> d(10.1);    cout << "double: " << d.getx() << endl;      MyClass<int> i(5);    cout << "int: " << i.getx() <<endl;    return 0;  }

Class Template PNU #include <iostream> using namespace std; template <class T, int N> class array {     T memblock[N];   public:     void setMember (int x, T value) { memblock[x]=value;}     T getMember (int x) { return memblock[x]; } }; int main () {   array <int,5> myInts;   array <float,5> myFloats;      myInts.setMember (0,100);   myFloats.setMember(3,3.1);   cout << myInts.getMember(0) << endl;   cout << myFloats.getMember(3) <<endl;   return 0; } 4

Class Template PNU #include <iostream> using namespace std; template <class Type1, class Type2> class MyClass {   Type1 i;   Type2 j; public:   MyClass(Type1 a, Type2 b) { i = a; j = b;  }   void show() { cout << i << ' ' << j << '\n';} }; int main()   MyClass<int, double> ob1(10, 0.23);   MyClass<char, char*> ob2('X', "AAAAAAA");   ob1.show();   ob2.show();   return 0; }