1 parametric polymorphism polymorphism techniques c++ templates
of 33
/33
1 Parametric Polymorphism Parametric Polymorphism Polymorphism Techniques C++ Templates
Post on 21-Dec-2015
230 views
Embed Size (px)
TRANSCRIPT
- Slide 1
- 1 Parametric Polymorphism Polymorphism Techniques C++ Templates
- Slide 2
- 2 Polymorphism: Overloading void f(int n) { cout print(); } }; struct Printable { Base* holder; template Printable(const T& t) : holder(new Holder (t)) { } Printable(const Printable& p) : holder(p.holder->clone()) { } virtual ~Printable() { delete holder; } void print() { holder->print(); } };">
- 29 Printable: the Right Way struct Base { virtual ~Base() { } virtual Base* clone() const = 0; virtual void print() = 0; }; template struct Holder : Base { U* u; Holder(const U& arg) : u(new U(arg)) { } ~Holder() { delete u; } Base* clone() const { return new Holder(*u); } void print() { u->print(); } }; struct Printable { Base* holder; template Printable(const T& t) : holder(new Holder (t)) { } Printable(const Printable& p) : holder(p.holder->clone()) { } virtual ~Printable() { delete holder; } void print() { holder->print(); } };
- Slide 30
- 30 Printable: The Assignment Operator struct Printable { Base* holder;... void swap(Printable& p) { Base* temp = holder; holder = p.holder; p.holder = temp; } Printable& operator=(const Printable& p) { Printable temp(p); swap(temp); return *this; } };
- Slide 31
- 31 Is This a Good Alternative? No! struct Printable { Base* holder;... Printable& operator=(const Printable& p) { if(this == &p) return *this; delete holder; holder = p.holder.clone(); return *this; } };
- Slide 32
- 32 C++ Templates: Main Points A functional programming language Turing complete Has the same power as any other programming language Runs while the compiler compiles We build a tree (of types) at compile-time When an error occurs the compiler prints the path from the root of this tree
- Slide 33
- 33 C++ Polymorphism: Templates vs. Inheritance Templates - pros: Type safety - as in collections Parametrize the protocol of a class Easier to define a compatible type Require only structural conformance A type parameter can serve as a super class Mixin Faster Inheritance pros: Polymorphism happens at run-time E.g.: type of object is determined by an input value Readable error messages No executable blow up Separate compilation (templates must be #included)