Upload
others
View
11
Download
0
Embed Size (px)
Citation preview
Lecture outline
● Part 1: Generic programming using templates in C++
● Part 2: Miscellaneous topics around C++
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
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
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.
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;}
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.
Type/object hierarchy
● Template → Class → Object
● Some prefer these names:class template → template class → class instance
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!
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.
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.
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
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;}
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; }};
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
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.
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;
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;
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.
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.
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”.
Part 2
● Generality trade-off● Different hierarchies● Use of memory in C++
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
Inheritance vs containment
● Inheritance creates a global internal scope● Inheritance - ”is a” relationship● Containment - ”has a” relationship
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.
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
Stack - Heap
● Class instance on the stack:// Definition within a functionMyClass a(20);
● Class instance on the heap:MyClass* pObject;pObject = new MyClass(20);
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.
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
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.
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
Assignment 2