31
Lecture outline Part 1: Generic programming using templates in C++ Part 2: Miscellaneous topics around C++

Part 1: Generic programming using templates in C++ C++ · Generic programming Coding without specifying type Python code is intrinsically generic to a certain extent, it depends on

  • Upload
    others

  • View
    11

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Part 1: Generic programming using templates in C++ C++ · Generic programming Coding without specifying type Python code is intrinsically generic to a certain extent, it depends on

Lecture outline

● Part 1: Generic programming using templates in C++

● Part 2: Miscellaneous topics around C++

Page 2: Part 1: Generic programming using templates in C++ C++ · Generic programming Coding without specifying type Python code is intrinsically generic to a certain extent, it depends on

Comparing languages

C and C++● Compiled languages● Closer to hardware

(variable types explicitly defined, memory allocation/deallocation, pointers)

Python● Script language● Higher abstraction level

(generic programming, automatic memory handling etc.)

100010101... def sqr(x):return x*x

double sqr(double x) {return x*x;

}machine instructions higher abstraction level

Page 3: Part 1: Generic programming using templates in C++ C++ · Generic programming Coding without specifying type Python code is intrinsically generic to a certain extent, it depends on

Generic programming

● Coding without specifying type● Python code is intrinsically generic to a certain

extent, it depends on interfaces rather than types.

● Python example:def max(x, y):

if x > y: return x else: return y

Page 4: Part 1: Generic programming using templates in C++ C++ · Generic programming Coding without specifying type Python code is intrinsically generic to a certain extent, it depends on

Max function using overloading

● Several functions can have the same name in C++, this is called function overloading.

● For int:int max(int x, int y) { return x > y ? x : y;}

● For float:float max(float x, float y) {

return x > y ? x : y;}

● But it seems unnecessary to specify the same procedure in different ways.

Page 5: Part 1: Generic programming using templates in C++ C++ · Generic programming Coding without specifying type Python code is intrinsically generic to a certain extent, it depends on

Max function using templates

● In statically typed languages, such as C++, special constructions are needed for defining generic code. In C++ these are called templates

● A function template in C++ removes the redundancy:

template <typename T>T max(T x, T y){ return x > y ? x : y;}

Page 6: Part 1: Generic programming using templates in C++ C++ · Generic programming Coding without specifying type Python code is intrinsically generic to a certain extent, it depends on

Template format

● Function template:template <typename T>function declaration

● Class template:template <typename T>class declaration

● typename can be replaced with class. There is no difference in semantics.

Page 7: Part 1: Generic programming using templates in C++ C++ · Generic programming Coding without specifying type Python code is intrinsically generic to a certain extent, it depends on

Type/object hierarchy

● Template → Class → Object

● Some prefer these names:class template → template class → class instance

Page 8: Part 1: Generic programming using templates in C++ C++ · Generic programming Coding without specifying type Python code is intrinsically generic to a certain extent, it depends on

Function template example 2

#include <iostream>#include <string>

using namespace std;

template<typename T>void Swap(T& a, T& b){ T temp = b; b = a; a = temp;}

int main(){ string s1 = "world!"; string s2 = "Hello, "; Swap( s1, s2 ); cout << s1 << s2 << endl;}

● Output:Hello, world!

Page 9: Part 1: Generic programming using templates in C++ C++ · Generic programming Coding without specifying type Python code is intrinsically generic to a certain extent, it depends on

No type definition neededfor function templates

● Using a function template, is just like using any function.

string s1 = "world!"; string s2 = "Hello, "; Swap( s1, s2 );

● You can writeSwap<string>(s1, s2);

as well, but it's not necessary. The compiler deduce this from the arguments.

Page 10: Part 1: Generic programming using templates in C++ C++ · Generic programming Coding without specifying type Python code is intrinsically generic to a certain extent, it depends on

Function created by the template

void Swap(string& a, string& b){ string temp = b; b = a; a = temp;}

● This function is created as one of the first steps in the compile procedure.

Page 11: Part 1: Generic programming using templates in C++ C++ · Generic programming Coding without specifying type Python code is intrinsically generic to a certain extent, it depends on

Class template// Template class declarationtemplate <class T>class Pair { T first, second;public: Pair(T _first, T _second); T max();};

// Constructortemplate <class T>Pair<T>::Pair(T _first, T _second) :

first(_first),second(_second)

{}

// Member functiontemplate <class T>T Pair<T>::max() { if (first>second) return first; else return second;}

// Use of the class templatePair<int> pair1(36, 54);cout << pair1.max() << endl;

● Output:54

Page 12: Part 1: Generic programming using templates in C++ C++ · Generic programming Coding without specifying type Python code is intrinsically generic to a certain extent, it depends on

Class created by the template

// Pair<int> would correspond to:

// Class declarationclass Pair { int first, second;public: Pair(int _first, int _second); int max();};

// ConstructorPair::Pair(int _first, int _second ) :

first(_first),second(_second)

{}

// Member functionint Pair::max() { if (first>second) return first; else return second;}

Page 13: Part 1: Generic programming using templates in C++ C++ · Generic programming Coding without specifying type Python code is intrinsically generic to a certain extent, it depends on

Different coding styles

// Separate definition & declarationtemplate <class T>class Pair { T first, second;public: Pair(T _first, T _second); T max();};

// Constructortemplate <class T>Pair<T>::Pair(T _first, T _second) :

first(_first),second(_second)

{}

// Member functiontemplate <class T>T Pair<T>::max() { if (first>second) return first; else return second;}

// Combined definition & declarationtemplate <class T>class Pair { T first, second;public: Pair(T _first, T _second) : first(_first), second(_second) {};

T max() { if (first>second) return first; else return second; }};

Page 14: Part 1: Generic programming using templates in C++ C++ · Generic programming Coding without specifying type Python code is intrinsically generic to a certain extent, it depends on

Different types// Class declarationtemplate <class T, class U>class Pair { T first; U second;public: Pair(T _first, U _second);};

// Constructortemplate <class T, class U>Pair<T,U>::Pair( T _first, U _second ) :

first(_first),second(_second)

{}

// UsagePair<int,double> myPair

Page 15: Part 1: Generic programming using templates in C++ C++ · Generic programming Coding without specifying type Python code is intrinsically generic to a certain extent, it depends on

Non-type parameters

template <class T, int size>class Array { T buffer[size];};

...

// Using the template somewhereArray<int,10> arrayObject;

● For each different pairs of parameters, a new class definition is created. This could cause ”code bloat” meaning that many class definitions are created from one template which results in a large executable file.

Page 16: Part 1: Generic programming using templates in C++ C++ · Generic programming Coding without specifying type Python code is intrinsically generic to a certain extent, it depends on

Templates of templates,graph example

// The classes created from this template,// defines the data a graph node should contain.template <class T, class U>class NodeData { string sIdentifier; T a; U b;};

// For creating graph classestemplate <class T> class MyGraph { struct Node { T data; vector<Node*> neighbors; };

vector<Node> nodes;

...};

// Usage somewhere// A template instance is used as input for another templateMyGraph<NodeData<int, float>> myGraph;

Page 17: Part 1: Generic programming using templates in C++ C++ · Generic programming Coding without specifying type Python code is intrinsically generic to a certain extent, it depends on

Templates as template parameters

template <class T>class Template1 {public: T t;};

template <template<class A> class T>class Template2 {public: T<int> data;};

// Usage somewhere Template2<Template1> myInteger; myInteger.data.t = 10;

Page 18: Part 1: Generic programming using templates in C++ C++ · Generic programming Coding without specifying type Python code is intrinsically generic to a certain extent, it depends on

Templates

● Think of writing templates as writing ordinary functions or classes.

● Often you don't immediately see that a template would be good. Rather you see that you have similar classes or functions that do almost the same thing but for different types. Then you could consider merging the code into a single template.

Page 19: Part 1: Generic programming using templates in C++ C++ · Generic programming Coding without specifying type Python code is intrinsically generic to a certain extent, it depends on

Motivation: code reuse

● With functions, a piece of code can be reused in different parts of a program.

● With baseclasses, a common part of classes can be reused.

● With templates, code can be reused for different types.

Page 20: Part 1: Generic programming using templates in C++ C++ · Generic programming Coding without specifying type Python code is intrinsically generic to a certain extent, it depends on

Template drawbacks

● Can be difficult to understand the code and error messages related to it.

● Can be difficult to debug.● Can lead to ”code bloat”.

Page 21: Part 1: Generic programming using templates in C++ C++ · Generic programming Coding without specifying type Python code is intrinsically generic to a certain extent, it depends on

Part 2

● Generality trade-off● Different hierarchies● Use of memory in C++

Page 22: Part 1: Generic programming using templates in C++ C++ · Generic programming Coding without specifying type Python code is intrinsically generic to a certain extent, it depends on

Generality trade-off

● Generality can lead to:+ Fewer lines of code, easier to maintain+ Easy to use in new situations

● Specificity:+ Saves time when code reuse is unlikely+ Can be easier to understand

Page 23: Part 1: Generic programming using templates in C++ C++ · Generic programming Coding without specifying type Python code is intrinsically generic to a certain extent, it depends on

Inheritance vs containment

● Inheritance creates a global internal scope● Inheritance - ”is a” relationship● Containment - ”has a” relationship

Page 24: Part 1: Generic programming using templates in C++ C++ · Generic programming Coding without specifying type Python code is intrinsically generic to a certain extent, it depends on

Different hierarchies

● When structuring software or reading documentation, you often create or see graphs of how software components relate and depend on each other.

● It's good to know that there are many different kinds of such hierarchies, for example:

● function hierarchies (call trees)● type hierarchies in the form of:

- class trees, connections created from inheritance - composition trees

● Class trees are maybe the most common in documentations.

Page 25: Part 1: Generic programming using templates in C++ C++ · Generic programming Coding without specifying type Python code is intrinsically generic to a certain extent, it depends on

Use of memory in C++

● Stack Segment - local variables, return values, return addresses

● Data Segment - global data, static variables, string constants

● Code Segment - program instructions● Heap - when using new

Page 26: Part 1: Generic programming using templates in C++ C++ · Generic programming Coding without specifying type Python code is intrinsically generic to a certain extent, it depends on

Stack - Heap

● Class instance on the stack:// Definition within a functionMyClass a(20);

● Class instance on the heap:MyClass* pObject;pObject = new MyClass(20);

Page 27: Part 1: Generic programming using templates in C++ C++ · Generic programming Coding without specifying type Python code is intrinsically generic to a certain extent, it depends on

Structures on heap or stack?

● Stack when specifying a fixed array● Stack better for small temporary objects● Heap better for larger objects● new is often slow. Could be good to use a pool

allocator.

Page 28: Part 1: Generic programming using templates in C++ C++ · Generic programming Coding without specifying type Python code is intrinsically generic to a certain extent, it depends on

Tools

● Compilers:- GCC- Visual Studio Compiler (cl.exe)- Intel C++ Compiler

● IDE:- Eclipse- Microsoft Visual Studio (Windows)- Xcode (included in Mac OS X)

● CMake - for generating build and project files● Doxygen - for creating code documentation

Page 29: Part 1: Generic programming using templates in C++ C++ · Generic programming Coding without specifying type Python code is intrinsically generic to a certain extent, it depends on

Libraries

● Boost - General high quality library which is free to use.

● GUI:Qt - platform ind. Used to be GPL:ed.wxWidgets - platform independentWPF - Windows Presentation Foundation, hardware accelerated.

● Math:GSL - GNU Scientific Library. GPL.MKL - Math Kernel Library from Intel. Commercial product.

Page 30: Part 1: Generic programming using templates in C++ C++ · Generic programming Coding without specifying type Python code is intrinsically generic to a certain extent, it depends on

Related books

● The C++ Standard Library: A Tutorial and Reference, Nicolai M. Josuttis

● Beyond the C++ Standard Library: An Introduction to Boost, Björn Karlsson

● Effective C++: 55 Specific Ways to Improve Your Programs and Designs, Scott Meyers

Page 31: Part 1: Generic programming using templates in C++ C++ · Generic programming Coding without specifying type Python code is intrinsically generic to a certain extent, it depends on

Assignment 2