以代码示例的方式介绍模板编程的几个特性:
Templates and parametric polymorphism
Template parameters
Member functions of template classes
Object oriented patterns
Lambda expressions in C++11
Void pointer polymorphism in C
Template specification;

注脚

展开查看详情

1.An introduction to C++ template programming Hayo Thielecke University of Birmingham http://www.cs.bham.ac.uk/~hxt March 2015

2.Templates and parametric polymorphism Template parameters Member functions of template classes Object oriented patterns Lambda expressions in C++11 Void pointer polymorphism in C Template specialization

3.C++ polymorphism Templates Dynamic polymorphism When compile-time run-time Typing Type parameters Subtyping Efficiency + no runtime overhead - indirection via pointers - potential code bloat at runtime Related to OCAML and Haskell polymorphism Objective C messages Java generics Java methods ML functors Over the last two decades, templates have developed from a relatively simple idea to the backbone of most advanced C programming. (Stroustrup 2012, section 25.1)

4.C++ templates templates are important: Standard Template Library type-safe collections templates interact/collide with other C++ features templates allow compile-time computation ⇒ zero overhead templates are a different language design dimension from object-orientation one way to use them is similar to polymorphism in functional languages In this module, we will build on your knowledge of functional programming

5.Templates and polymorphism There are two kinds of templates in C++: 1. Class templates 2. Function templates These correspond roughly to polymorphic data types and polymorphic functions in functional languages.

6.Polymorphism in functional languages # [1; 2; 3];; - : int list = [1; 2; 3] type ’a bt = Leaf of ’a | Internal of ’a bt * ’a bt ;; # let twice f x = f ( f x ) ;; val twice : ( ’ a -> ’a ) -> ’a -> ’a = <fun >

7.Templates: keyword template template < typename T > struct s { ... T ... T ... }; Then instantiating the template with argument A in s<A> is like struct sA { ... A ... A ... }; Compare: λ calculus.

8.Templates: type parameter template < typename T > struct S { // members here may depend on type parameter T T data ; // for example a data member void f ( T ) ; // or a member function using t = T ; // or making t an alias for T };

9.Class template example template < typename T > struct Linked { T head ; Linked <T >* tail ; }; Class template - other keywords template < class T > class Linked { public : T head ; Linked <T >* tail ; };

10.Telling a template what to do We can pass types to templates We may also configure its behaviour sometimes called “policy”, “callbacks”, etc like higher-order functions there are many ways of doing this in C++ classes with static member functions function pointers function objects, “functors” lambda expressions (new in C++11)

11.Function template example We pass a type T and a class Ops that provides two operations. template < typename T , typename Ops > T fold ( Linked <T > * p ) { T acc = Ops :: initial () ; while ( p ) { acc = Ops :: bin ( acc , p - > head ) ; p = p - > tail ; } return acc ; } Note: we pass the class, not an object.

12.Class as argument of a template This class provides integer operations: struct IntOps { static int initial () { return 0; }; static int bin ( int x , int y ) { return x + y ; } }; In essence, this class is just a pair of functions.

13.Using the templates on int lists int main ( int argc , const char * argv []) { auto sumup = fold < int , IntOps >; Linked < int > x {3 , nullptr }; Linked < int > y {2 , & x }; std :: cout << sumup (& y ) ; return 0; }

14.Another class: string operations This provides string operations: class StrOps { public : static std :: string initial () { return " " ; }; static std :: string bin ( std :: string x , std :: string y ) { return x + y ; } };

15.Using the template on string lists int main ( int argc , const char * argv []) { Linked < std :: string > b = { " bar " , nullptr }; Linked < std :: string > a = { " foo " , & b }; auto sumupstr = fold < std :: string , StrOps >; std :: cout << sumupstr (& a ) << " \ n " ; return 0; }

16.Function pointer as template argument Here we pass a type T, a value of type T and a binary operation on T template < typename T , T init , T (* bin ) (T , T ) > T fold2 ( Linked <T > * p ) { T acc = init ; while ( p != nullptr ) { acc = bin ( acc , p - > data ) ; p = p - > next ; } return acc ; }

17.Function pointer as template argument: using it inline int sum ( int x , int y ) { return x + y ; } auto sumup2 = fold2 < int , 0 , sum >;

18.Member functions of template classes template < typename T > struct Linked { T data ; Linked <T >* next ; void apply_each ( void (* f ) ( T ) ) ; }; template < typename T > void Linked <T >:: apply_each ( void (* f ) ( T ) ) { T * p = data ; while ( p ) { f (p - > data ) ; p = p - > next ; } }

19.Functors/function objects in C++ A function object is an object that can be used like a function. One of its member functions overloads the function call syntax () Such an object can have its own data members. We can create function object dynamically, unlike C functions. In functional programming terms, function objects simulate closures. Function objects are often used with templates. Objects cannot be template parameters, only function parameters.

20.Function object example // class for curried addition function class cadd { private : int n ; public : cadd ( int n ) { this - > n = n ; } int operator () ( int m ) { return n + m ; } }; int main ( int argc , const char * argv []) { // make a new function object in local var cadd addfive (5) ; cout << addfive (7) ; } This prints 12.

21.Function objects and templates template < typename T , typename Op > T twice ( T x , Op f ) { return f ( f ( x ) ) ; } int main ( int argc , const char * argv []) { cadd addfive (5) ; // create function object cout << twice < int , cadd >(10 , addfive ) << endl ; cout << twice (10 , addfive ) << endl ; } This prints 20 twice.

22.Virtual member function templates? Suppose we want a worker that computes XML from a tree of ints. template < typename T > class polyworker { public : virtual T workplus (T , T ) ; virtual T workconstant ( int ) ; };

23.Virtual member function templates? Suppose we want a worker that computes XML from a tree of ints. template < typename T > class polyworker { public : virtual T workplus (T , T ) ; virtual T workconstant ( int ) ; }; class Base { public : template < typename T > virtual T employ ( polyworker <T >*) = 0; // compilation error }; See our paper on A Type-theoretic Reconstruction of the Visitor Pattern

24.Visitor pattern The Visitor pattern is one of the classic patterns from the “Gang of Four” OO Patterns book Design patterns : elements of reusable object-oriented software Related patterns are Composite and Interpreter worker and employ are like visit visitor and accept in GoF GoF visitors use local state in the object rather than return types; they have void return types The GoF book is from 1995 There is a lot of emphasis on inheritance Since them, C++ has taken on more ideas from functional programming (e.g., lambda, auto)

25.Some object-oriented patterns Behavioural patterns are related Composite = object-oriented idiom to define trees Visitor = tree walker, internal vs external visitor stateful vs functional Interpreter, special case of Composite for a grammar of a language Iterator: internal visitors from lambda expression with reference

26.Visitor pattern as per Gang of Four 1 class gofvisitor { public : virtual void visitplus ( class plus *) = 0; virtual void visitconstant ( class constant *) = 0 ; }; class plus : public gofbase { class gofbase * p1 , * p2 ; public : plus ( gofbase * p1 , gofbase * p2 ) { this - > p1 = p1 ; this - > p2 = p2 ; } void accept ( gofvisitor * v ) { p1 - > accept ( v ) ; p2 - > accept ( v ) ; v - > visitplus ( this ) ; }

27.Visitor pattern as per Gang of Four 2 class plus : public gofbase { gofbase * p1 , * p2 ; public : plus ( gofbase * p1 , gofbase * p2 ) { this - > p1 = p1 ; this - > p2 = p2 ; } virtual void accept ( gofvisitor * v ) { p1 - > accept ( v ) ; p2 - > accept ( v ) ; v - > visitplus ( this ) ; } };

28.Visitor pattern as per Gang of Four 3 Because the return type is void, the visitor must use internal state to accumulate its result: class countplusvisitor : public gofvisitor { int count ; public : void visitconstant ( class constant * p ) {} void visitplus ( class plus * p ) { count ++; } int getcount () { return count ; } countplusvisitor () { count = 0; } };

29.Internal iterator and lambda expressions Now suppose we want to do some work only at the leaf nodes on the data, not the internal nodes that determine the shape of the data structure. We do not need a whole class. A function to be called on each leaf.

30.Lambda expressions in C++11 Lambda from the λ-calculus. Here is a “lambda expression”: [=] ( int x ) { return x + a ; } It is like fun x -> x + a in OCAML or λx.x + a Variable a needs to be in scope. Variables can be captured by reference: [&] ( int x ) { return x + a ; }

31.Lambda expressions in C++11 Lambda expressions in C++ provide two different new features: 1. anonymous functions 2. closures (capturing variables from a surrounding context) Compare: gcc nested functions.

32.Lambda expressions in C++11 Lambda from the λ-calculus. Here is a “lambda expression”: [=] ( int x ) { return x + a ; } It is like fun x -> x + a in OCAML or λx.x + a Variable a needs to be in scope. Variables can be captured by reference: [&] ( int x ) { return x + a ; }

33.Lambda calculus: anonymous functions (λa.a + a)(2)

34.Lambda calculus: anonymous functions (λa.a + a)(2) 2+2 4

35.Lambda calculus 2 (λf .f (3)) (λa.a + a)

36.Lambda calculus 2 (λf .f (3)) (λa.a + a) (λa.a + a) (3)

37.Lambda calculus 2 (λf .f (3)) (λa.a + a) (λa.a + a) (3) 3+3 6

38.Lambda calculus 3 (λx .(λy .x + y )) (2) (3)

39.Lambda calculus 3 (λx .(λy .x + y )) (2) (3) (λy .2 + y ) (3)

40.Lambda calculus 3 (λx .(λy .x + y )) (2) (3) (λy .2 + y ) (3) 2+3 5

41.Lambda calculus 3 (λx .(λy .x + y )) (2) (3) (λy .2 + y ) (3) 2+3 5 Real programming languages do not actually copy parameters into the function. Closures are used to implement lambda expressions. In C++, we need to be aware of what happens in memory.

42.Lambda expressions are implemented by closures [=] ( int x ) { return x + x ; }

43.Lambda expressions are implemented by closures [=] ( int x ) { return x + x ; } Closed function: no free variables. Easy to implement, like a function pointer in C.

44.Lambda expressions are implemented by closures [=] ( int x ) { return x + x ; } Closed function: no free variables. Easy to implement, like a function pointer in C. [=] ( int x ) { return x + a ; }

45.Lambda expressions are implemented by closures [=] ( int x ) { return x + x ; } Closed function: no free variables. Easy to implement, like a function pointer in C. [=] ( int x ) { return x + a ; } Not closed due to a: must build a closure containing a

46.Lambda expressions are implemented by closures [=] ( int x ) { return x + x ; } Closed function: no free variables. Easy to implement, like a function pointer in C. [=] ( int x ) { return x + a ; } Not closed due to a: must build a closure containing a [&] ( int x ) { return x + a ; }

47.Lambda expressions are implemented by closures [=] ( int x ) { return x + x ; } Closed function: no free variables. Easy to implement, like a function pointer in C. [=] ( int x ) { return x + a ; } Not closed due to a: must build a closure containing a [&] ( int x ) { return x + a ; } Closure with pointer to a

48.Template std::function The template std::function gives general function types. Example: type of functions taking two integers and returning a float is function < float ( int , int ) > Useful for typing lambda expressions. The same type can be used for C-style function pointers and C++ lambda expressions.

49.Lambdas as function parameters int twice ( function < int ( int ) > g , int n ) { return g ( g ( n ) ) ; } What does this print? cout << twice ([] ( int m ) { return m + 1; } , 10) << endl ;

50.Lambdas as function parameters int twice ( function < int ( int ) > g , int n ) { return g ( g ( n ) ) ; } What does this print? cout << twice ([] ( int m ) { return m + 1; } , 10) << endl ; It prints 12.

51.Lambdas as function results function < int ( int ) > f ( int x ) { return [=] ( int y ) { return x + y ; }; } int main ( int argc , const char * argv []) { auto g = f (2) ; cout << g (3) << endl ; cout << g (4) << endl ; } What does this print?

52.Lambdas as function results function < int ( int ) > f ( int x ) { return [=] ( int y ) { return x + y ; }; } int main ( int argc , const char * argv []) { auto g = f (2) ; cout << g (3) << endl ; cout << g (4) << endl ; } What does this print? It prints 5 and 6.

53.Lambdas and automatic variables function < int () > seta () { int a = 11111 ; return [=] () { return a ; }; } int geta ( function < int () > f ) { int b = 22222; return f () ; }; What does this print: cout << geta ( seta () ) << endl ;

54.Lambdas and automatic variables function < int () > seta () { int a = 11111 ; return [=] () { return a ; }; } int geta ( function < int () > f ) { int b = 22222; return f () ; }; What does this print: cout << geta ( seta () ) << endl ; It prints 11111.

55.Lambdas and automatic variables, by reference function < int () > seta () { int a = 11111 ; return [=] () { return a ; }; } int geta ( function < int () > f ) { int b = 22222; return f () ; }; What does this print: cout << geta ( seta () ) << endl ;

56.Lambdas and automatic variables, by reference function < int () > seta () { int a = 11111 ; return [=] () { return a ; }; } int geta ( function < int () > f ) { int b = 22222; return f () ; }; What does this print: cout << geta ( seta () ) << endl ; It prints 22222 when I tried it. Undefined behaviour.

57.Lambdas and capture by reference Lambda expressions bring some more functional programming into C++. Lambda are usefully combined with templates and type inference.

58.Lambdas and capture by reference Lambda expressions bring some more functional programming into C++. Lambda are usefully combined with templates and type inference. But C is lurking underneath. C++ references are implemented much like C pointers. Capture by reference [&] (...) { ... }; requires understanding of object lifetimes, e.g. stack.

59.Currying in C++ In OCaml: let curry f x y = f (x , y ) ;;

60.Currying in C++ In OCaml: let curry f x y = f (x , y ) ;; Using C++ templates and lambda, the above becomes: template < typename A , typename B , typename C > function < function < C ( B ) >( A ) > curry ( function < C (A , B ) > f ) { return ([=] ( A x ) { return ([=] ( B y ) { return f (x , y ) ; }) ; }) ; } What does this print: auto cadd = curry < int , int , int >( add ) ; cout << cadd (100) (10) << endl ;

61.Currying in C++ In OCaml: let curry f x y = f (x , y ) ;; Using C++ templates and lambda, the above becomes: template < typename A , typename B , typename C > function < function < C ( B ) >( A ) > curry ( function < C (A , B ) > f ) { return ([=] ( A x ) { return ([=] ( B y ) { return f (x , y ) ; }) ; }) ; } What does this print: auto cadd = curry < int , int , int >( add ) ; cout << cadd (100) (10) << endl ; It prints 110.

62.Lambda expression as internal iterator 1 template < typename T > class bintree { public : virtual void employ ( std :: function < void ( T ) >) = 0; }; template < typename T > class leaf : public bintree <T > { T data ; public : leaf ( T x ) { data = x ; } void employ ( std :: function < void ( T ) > f ) { f ( data ) ; } };

63.Lambda expression as internal iterator 2 template < typename T > class internal : public bintree <T > { class bintree <T > * left , * right ; public : internal ( bintree <T > * p1 , bintree <T > * p2 ) { left = p1 ; right = p2 ; } void employ ( std :: function < void ( T ) > f ) { left - > employ ( f ) ; right - > employ ( f ) ; } };

64.Lambda expression as internal iterator 3 int sum1 ; void sumfun ( int n ) { sum1 += n ; } int main ( int argc , const char * argv []) { int sum2 ; class bintree < int > * p = new internal < int >( new leaf < int >(4) , new leaf < int >(3) ) ; sum1 = 0; p - > employ ( sumfun ) ; // employ a C function std :: cout << sum1 << std :: endl ; sum2 = 0; p - > employ ([&] ( int x ) { sum2 += x ; }) ; // employ a C ++ lambda std :: cout << sum2 << std :: endl ; }

65.Lambda expression as internal iterator 4 The above is a good use of lambda expressions. sum2 = 0; p - > employ ([&] ( int x ) { sum2 += x ; }) ; A small piece of code made on the fly. In this case, by reference is safe.

66.Templates and lambda calculus (λx .(λy .x + y )) (2) (3)

67.Templates and lambda calculus (λx .(λy .x + y )) (2) (3) (λy .2 + y ) (3)

68.Templates and lambda calculus (λx .(λy .x + y )) (2) (3) (λy .2 + y ) (3) 2+3 5

69.Templates and lambda calculus (λx .(λy .x + y )) (2) (3) (λy .2 + y ) (3) 2+3 5 template < int x > int templatecurry ( int y ) { return x + y ; } ... cout << templatecurry <2 >(3) << endl ;

70.Void pointer polymorphism in C Quicksort from C library: void qsort ( void * base , size_t num , size_t size , int (* compar ) ( void * , void *) ) ; Comparison function using void pointers: int comparefloat ( void *p , void *q) { if ( *( float *) p < *( float *) q ) return -1; if ( *( float *) p == *( float *) q ) return 0; if ( *( float *) p > *( float *) q ) return 1; }

71.Void pointer polymorphism example 1 struct Linked { void * data ; struct Linked * next ; };

72.Void pointer polymorphism example 2 void * fold ( struct Linked *p , void * initial , void *(* bin ) ( void *x , void * y ) ) { void * acc ; acc = initial ; while ( p ) { acc = bin ( acc , p - > data ) ; p = p - > next ; } return acc ; }

73.Void pointer polymorphism example 3 void * ptr2sum ( void *x , void * y ) { int * p ; p = malloc ( sizeof ( int ) ) ; * p = *( int *) x + *( int *) y ; return p ; }

74.Template specialization Template specialization is like pattern matching in functional languages specialization = instantiation We can pattern-match on types or values Templates can be recursive One possibility: compute functions at compile-time, e.g. factorial More serious: optimize templates for particular type parameters. We can write dependent types, like in Agda

75.Values and types parameterized on values and types ↓ parameterized on → Value Type Value Function Polymorphic function Type Dependent type Polymorphic type Dependent type example: template < int n > struct s { // structure may depend on int parameter }; Arrays are also dependent types, but they decay into pointers in C/C++.

76.Template specialization example: parsing C types template < typename T > struct NameofType ; template < typename T , typename S > struct NameofType < T (*) ( S ) > { static void p () { std :: cout << " pointer to function returning a " ; NameofType <T >:: p () ; std :: cout << " and taking an argument of type " ; NameofType <S >:: p () ; } };

77.parsing C types - part 2 template < > struct NameofType < int > { static void p () { std :: cout << " int " ; } }; template < > struct NameofType < float > { static void p () { std :: cout << " float " ; } };

78.parsing C types - part 3 template < typename T > struct NameofType < T * > { static void p () { std :: cout << " pointer to " ; NameofType <T >:: p () ; } }; template < typename T > struct NameofType < T [] > { static void p () { std :: cout << " array of " ; NameofType <T >:: p () ; } };

79.N-dimensional matrix template example template < typename T , int n > struct ndimMatrix ; template < typename T > struct ndimMatrix <T , 0 > { T m []; }; template < typename T , int n > struct ndimMatrix { ndimMatrix <T , n - 1 > m []; };

80.Template template parameters template < template < typename > class Cont > struct UseContainer { Cont < int > key ; Cont < float > value ; }; ... UseContainer < vector > uc ;