Template metaprogramming

Size: px
Start display at page:

Download "Template metaprogramming"

Transcription

1 Template metaprogramming Peter Jönsson Alex Robsahm Mälardalen University Department of Computer Science and Engineering PO Box 883 SE Västerås, Sweden May

2 Contents 1 Introduction 5 2 How templates work 7 3 Generating values Factorial example Trigonometric example Generating code Simple loop unroll Bubblesort unrolled Conditional tests Expression templates Related techniques Mixin Traits Pros and cons with template metaprogramming Pros Cons Conclusion 24 2

3 List of Figures 1 Template max-function A max-function implemented as a C macro A template stack class Prime numbers printed as compiler errors Specialized template for comparing char * factorial.c template.cc Output of compiled template metaprogram Assembler of template program C function for computing sin series expansion template metaprogram for computing sin series expansion Example usage Loop unrolling program The unrolled loop Outer bubblesort loop Inner bubblesort loop Bubblesort swap If test operation Switch test operation Psudeocode for vector calculation Tree and node templates Generated code Implementation of mixin

4 Abstract Generic programming is the idea of defining functions and classes without committing to a type. The correct type is instead chosen by the compiler during compilation. This makes it possible to remove redundant algorithms that only differ in types and to create container classes such as a stack with a single definition of the said class. In the C++ programming language this is available to us through the use of templates and has been a big part of the success of C++ since it was introduced. It is also available in other programming languages such as Eifell, Ada and Java (JDK 1.5). It was discovered in 1994 almost by accident that the template mechanism in C++ provides a rich facility for computation during compile time. This technique was named template metaprogramming and has grown to become a part of modern C++ programming. In this article we will look at how template metaprogramming can be used to compute values and to generate code. We will also look at two related techniques, mixin and traits. We will examine where and when to use template metaprogramming since it creates problems that we don t normally have to deal with using normal C++ code.. This is largely due to the fact the template metaprogramming is based on abusing the compiler and the use of advanced C++ constructs. 4

5 1 Introduction One of Bjarne Stroustrup design aims for C++ was the support for generic programming [1]. Though C++ did not have support for it from the start, it was only added to the language during the time period of This was a few years after C++ was first commercially available (1985) but before the formal standardization of C++ started in All of Bjarnes design aims for the C++ programming language can be seen below. C++ makes programming more enjoyable for serious programmers. C++ is a general-purpose programming language that is a better C supports data abstraction supports object-oriented programming supports generic programming template<class T> T max(t a, T b ) return ( a > b )? a : b ; Figure 1: Template max-function Generic programming in C++ is provided by templates. This is a way of making it possible to use the same algorithm with different data types thus reducing the need for duplicated code. A simple example of a template based function that takes two elements and returns the largest one is shown in figure 1. This algorithm will work for all classes and types for which the < operator has been defined. #d e f i n e MAX( i, j ) ( ( ( i ) > ( j ) )? ( i ) : ( j ) ) Figure 2: A max-function implemented as a C macro This is somewhat similar to the C macro seen in figure 2 though when using macros in C there is no type checking so there are no guarantees that i and j are of the same type [6]. Using templates we can ensure type safety with the help of the compiler. Also the C preprocessor will expand the macro in every place where it is used. This will result in redundant code in the resulting program. Templates do not work in this way as we shall explain later, So templates are a much nicer solution to this problem. 5

6 Templates can also be used to create generic collection classes called class templates where all type information in the class is parameterized using the template. Using this technique it is possible to create for example a Stack class that can be used for creating stacks that hold different types and classes. A template stack class is shown in figure 3. template<class T> class Stack T v ; int max size ; int top ; Stack ( int s ) top = 0 ; v = new T[ max size = s ] ; Stack ( ) delete [ ] v ; void push (T c ) v [ top ++] = c ; T pop ( ) return v[ top ] ; ; Figure 3: A template stack class This was the original intention of the introduction of generic programming through templates and has been used with big success in many applications and especially in the C++ standard template library (STL). A good short introduction to the standard template library can be found at SGI [7]. In 1994 during a ISO/ANSI C++ standardization meeting Erwin Unruh circulated a small program that computed primes numbers during template instantiation and printed them as compile time error messages [13]. The program written by Unruh was designed so that the binding of the template parameter failed, and the compiler printed a list of primes as part of the compiler error message. A sample of the printout of the error messages can be seen in figure 4. Type enum cant be converted to type D<2> Type enum cant be converted to type D<3> Type enum cant be converted to type D<5> Type enum cant be converted to type D<7> Type enum cant be converted to type D<11> Figure 4: Prime numbers printed as compiler errors This was to great surprise to many people, including C++ creator Bjarne Stroustrup! [13]. The program was of course of no real use but the concept of computing values during compilation had been shown and more work was done 6

7 on this. The breakthrough for template metaprogramming in the world outside the ISO/ANSI C++ standardization halls was an article by Todd Veldhuizen [4]. In this article Veldhuizen presented several simple examples of how to use this newly found tool. So this little program that did not even compile had sparked a explosion of research and experimenting with templates. After many long nights and abused compilers what we now call template metaprogramming was formed. There are several different techniques where template metaprogramming has been used. The most used being metafunctions for computing types and numbers and metafunctions for generating code. Computing values during compile time has its obvious advantages and can be used to create fast numerical libraries. Code generation is commonly used for loop unrolling in algorithms to achieve speed increase. We will examine both these applications and present some easy to understand examples for both. Finally we will look at the problems that arise from using template metaprogramming. They are considerable and we try to show how to maximize the use of template metaprogramming while minimizing the problems. But first we will look at how templates work. 2 How templates work It s important to realize that templates are not class and member definitions. Instead they are instructions to the C++ compiler about how to generate class and member function definitions. A particular actualization of a template, such as a Stack class for String objects, is called an instantiation or specialization. Instantiation of a template is when we have a template like the Stack class in figure 3 and want one stack of integers and another of doubles. The compiler will then instantiate one version that takes integers and another that takes doubles. There will only be one instantiation of a template with a particular type in the whole program, this is to reduce code size. How the compiler achieves this beyond the scope of this article. It is also different between compiler implementations. The fact that the instantiation of templates is a recursive process is how it is possible to achieve template metaprogramming. When the compiler instantiates a template it might find that another instantiation of some other template is needed. It then instantiates that template, which might require that instantiation of yet another template and so on. Template specialization is a definition for a particular type or class that is to be used instead of the general template. Sometimes there might be a need to change a template for when a particular type is instantiated, in that case you 7

8 create a specialization template. If we refer to the template max-function in figure 1. It is perfectly legal, from the standpoint of the compiler, to compare two char * (pointer to array of character). Indeed this will work when compiled but the behavior might not be what we expected since the < operator will compare the memory addresses of the pointers and not the strings that they point out. We should use the strncmp function instead of the < operator. So we will make a specialized template for this type. Now when the compiler is faced with a choice of a general template and one that has a specialized type it will always use the specialized template. A specialized template function of the max-function can be seen in figure 5. template<> char max( char a, char b ) return strncmp ( a, b, MAX)? a : b ; Figure 5: Specialized template for comparing char * So far the template examples we have looked at all have been somewhat like a preprocessor, albeit a much more powerful one than the preprocessor in the C programming language. It is totally possible to create a macro that can be used somewhat in the same way as the template max function we have defined here. Microsoft Developer Network [6] lists some major problems with macros that templates do not suffer from. The differences between macros and template functions are : There is no type checking done by the preprocessor when expanding the macro. So it is totally possible to try to compare types that are not equal. With templates type checking is provided by the compiler. The parameters are evaluated twice. For example if one of the parameters has a post incremental operator that increment will be performed twice. Since the macros are expanded by the preprocessor all compiler errors will refer to the expanded macro and not the macro itself. The macro will also show up in its expanded form when debugging. But templates are not just improved macros with a more powerful preprocessor that perform type checking. Further investigation into the behavior found by Unruh [13] showed that templates in C++ is in it itself is a Turing complete language. Though in practice there might be some limits on how powerful 8

9 template metaprogramming is, the usual bottleneck is the compiler since it is pushed to the limit and sometimes over it when using template metaprogramming. In computational theory a Turing-complete language is said to be a language that has the equivalent computing power to a universal Turing machine. In other words the universal Turing machine and the Turing-complete language can both emulate each other. Though we usually overlook the requirement for infinite memory, or tape in the case of the universal Turing machine, when we do this comparison. A more formal proof of the Turing completeness of templates is presented by Todd L. Veldhuizen in [2] where he implements a Turing machine using templates. 3 Generating values The most basic application of template metaprogramming is the computing of values. It is very easy to see how this could be used to optimize software that uses many numerical calculations such as engineering applications and computer games. Though there are some restrictions that we will look at as well. 3.1 Factorial example We will first show an ordinary function for computing the factorial of a natural number N. The factorial of N (mathematically speaking N!) is the product of all the numbers from 1 to N. For example 5! is The program is printed in figure 6 and as we can see it uses recursion just as template metaprogramming does. int f a c t o r i a l ( int n ) return ( n = = 0 )? 1 : n f a c t o r i a l (n 1); int main ( int argc, char argv [ ] ) p r i n t f ( %d\n, f a c t o r i a l ( 1 0 ) ) ; return 0 ; Figure 6: factorial.c Recursion is much more important to template metaprogramming than it is to ordinary C++. This is in contrast to functional programming languages 9

10 such as Haskell where recursion is all that is used. The reasons for the limited use of recursion outside the functional paradigm are several. One of the reason are that recursion can be less efficient than a non recursive solution. Though we suspect that this is not the biggest reason today, it is more likely that the reason is cultural. Programmers that have been exposed to functional languages, such as Haskell, learn how to think recursively and there are examples to learn from everywhere. The same cannot be said for when you are programming in C++ where almost all solutions are iterative. This can be a bit of an obstacle since the programming paradigm for template metaprogramming is functional not imperative or object oriented as the heritage from C and C++ might suggest. This of course means that C++ is a truly multi paradigm programming language where we can choose between several different styles of programming but still program in the same language. This of course will increase the complexity of the code and might reduce the readability. But when used wisely it can be a very powerful tool. In figure 7 we have a template metaprogram for computing the factorial of 10 just as the non template version we presented in figure 6. This looks a bit different from how we have used template so far so we will explain what is going on. #i n c l u d e < iostream > using namespace std ; template<int n> struct F a c t o r i a l s t a t i c const RET = F a c t o r i a l <n 1>::RET n ; ; template<> struct F a c t o r i a l <0> s t a t i c const RET = 1 ; ; int main ( int argc, char argv ) cout << F a c t o r i a l <10 >::RET << endl ; return 0 ; Figure 7: template.cc First we have the general template that will be instantiated for all n that are 10

11 bigger than 0. From this template we will get a structure which only contain a static variable called RET. It is a very good idea to always name this variable the same in all template meta functions since that way we do not have to remember several different names. Another choice for the name could be value since that is used in the template metaprogramming library called Boost MPL [10]. We also see that it is in this template that we have the recursive call. But there was a an end to the recursion, a base case, for when we should stop the recursion and let the value of RET be computed. To do this we have a template specialization that matches the numerical value of 0. This template sets its RET value to 1 and contains no further recursion making it possible to compute the real value of the factorial of n. In both programs we have included a main function that prints the value of the factorial of 10. A simple test execution of both programs give us that 10! is The test run printout can be seen in figure 8. This shows us that using template metaprograms we can indeed compute numerical values, but how do we know that the value was really computed during the compilation? We cannot measure any large time differences between the two programs. But if we use the -S flag when compiling the source code of the template metaprogram with GCC[11] we will get the assembler that the compiler creates instead of an executable file.. / template Figure 8: Output of compiled template metaprogram We then look through the assembler code and we find that indeed was already in the assembler source, so the value was computed during the template instantiation! The relevant part of the assembler can be found in figure 9. There is large limitation to what we can compute using this technique. We need to know what n we are to compute the factorial of. c a l l main movl , 4(% esp ) movl ZSt4cout, (% esp ) Figure 9: Assembler of template program 11

12 3.2 Trigonometric example In this example we will study another numerical calculation. We aim to approximate the trigonometric function sin. To write a compile time function for computing sin we are going to use a series expansion. A series expansion is representation of a function as a sum of powers in of its variables, or by a sum of powers of another (usually elementary) function f(x) [8]. The series expansion for the sin function is as follows : sin x = x x3 3! + x5 5! x7 7! +... This looks like something we could implement using template metaprogramming. But first we show a run time version of a function for computing the series. We can see i figure 10 that the j is the number of terms we will have in the series. The bigger the value the more precise will our sin value be at the cost of execution time. But if we moved this computation to compile time using template metaprogramming we could compute all sin values with exactly the precision we want. f l o a t s i n e ( f l o a t x, int j ) f l o a t v a l = 1 ; for ( int k = j 1 ; k >= 0; k ) v a l = 1 x x /(2 k+2)/(2 k+3) v a l ; return x v a l ; Figure 10: C function for computing sin series expansion In the template metaprogramming version of the expansion series we let x = 2 π I N This permits us to pass x using two integer template parameters (I and N) so we can write as in figure 11. The code looks a bit cryptic but now we will try to explain it. The first template is the one we will instantiate when we want to have a sin value, it in turn will instantiate the recursive template. In SineSeries J is the number of terms exactly like the non template example. This could of course be a define or a supplied parameter to the first template metafunction. The number of terms could be decided as a trade of between accuracy and the increased compile time. 12

13 template<int N, int I> struct Sine s t a t i c const RET = ( I 2 M PI/N) S i n e S e r i e s <N, I, 1 0, 0 > : :RET; ; template<int N, int I, int J, int K> struct S i n e S e r i e s enum go = (K+1!= J ) ; s t a t i c const int RET = 1 ( I 2 M PI/N) ( I 2 M PI/N)/(2 K+2)/(2 K+3) S i n e S e r i e s <N go, I go, J go, (K+1) go >::RET; ; template<> struct S i n e S e r i e s <0,0,0,0 > s t a t i c const int RET = 1 ; ; Figure 11: template metaprogram for computing sin series expansion Now we could just use this as in figure 12 to get the value. This is very useful in applications where sine and cosine values are needed, such as computing Fast Fourier Transforms [9]. Usually a lookup table was precomputed and then entered intothe program but by using template metaprogramming there is no longer any need for this. This is not the only example where we could use this technique to speed a program more but it should give you a general idea on where it could be used. f l o a t f = Sine <32,5 >::RET Figure 12: Example usage 4 Generating code Template metaprogramming might be seen as a neat trick so far, but together with ordinary code great optimizations can be achieved. As an example the programmer can create the body of a loop and then have a template metaprogram repeat the code so that a time consuming loop can be avoid. All code generation is based on the idea of letting the compiler build and choose which code to compile based on parameters at compile time. The optimizations are unrolled loops, the right statement in if and switch statements, all of these speeds up a 13

14 program. Template metaprogramming offers a much better control in selecting the code to be compiled than traditional preprocessor directives such as #ifdef. 4.1 Simple loop unroll During the loop for(int i=0; i<100; i++) at least 100 additions and test operations on i will be performed. Thanks to template metaprogramming we can unroll the loop and have the compiler inline the algorithm. By doing so we will have a speed increase due to the hundreds of additions and test operations that never takes place. As all loops in template metaprogramming the code for loop unrolling is recursive. In figure 13 we see the template metaprogram. The recursive call is pretty simple, all the magic is in the inline keyword. The inline keyword tells the compiler that we want to the replace the function call with the actual code that resides in the function. This will of course remove the overhead of the function call all together. template< int i > class LOOP s t a t i c inline void Do( ) LOOP< i 1 >::Do ( ) ; cout << i << " " ; ; template <> class LOOP< 0 > s t a t i c inline void Do( ) cout << i << " " ; ; Figure 13: Loop unrolling program So when we write LOOP::Do< 4 > in our program the compiler will unroll the loop and replace it with the code in figure 14. Of course this simple example does not really make a big difference in run time but the idea can be applied to time consuming loops in software where running time is important, such as 14

15 for example computer games. Instead of doing four computations and five test operations the metaprogram generates five rows of straight forward code. This optimization reaches a peak when the code generated grows too large. One other big advantage to using template metaprogramming to unroll your loops instead of doing by hand is that the source of the program will never contain the unrolled loop, only when the code is compiled will it be optimized. So in effect template meta programming act as an optimizing compiler but with the programmer in control instead of the compiler. cout << 0 << " " ; cout << 1 << " " ; cout << 2 << " " ; cout << 3 << " " ; cout << 4 << " " ; Figure 14: The unrolled loop 4.2 Bubblesort unrolled In this example we will take the well known sorting algorithm bubblesort and replace it with a version with the loops. Though bubblesort is most famous for being one of the worst algorithms it is not so terrible on small number of elements and on data that is almost sorted. The class IntBubbleSort in figure 15 makes up the outer loop. This is the template meta function which we will call when we want to use the bubblesort. We also have a base case for the recursion as usual in all the examples we have seen. The class IntBubbleSortLoop in figure 16 is the inner loop. This is also where we call the swap function (figure 17) that is called for every pair. The comparison of the two integers is done here and if they need to be swapped, they are. The comparison of the two integers is done in the swap function instead of being done in the inner loop. Because of the difficulty to make a base case with two parameters the algorithm works with a stop flag named go. When go is false the recursive call goes to the base case of the recursion. 15

16 template< int N > class IntBubbleSort s t a t i c inline void s o r t ( int data ) IntBubbleSortLoop < N 1, 0 >:: loop ( data ) ; IntBubbleSort < N 1 >:: s o r t ( data ) ; ; template<> class IntBubbleSort < 1 > s t a t i c inline void s o r t ( int data ) ; Figure 15: Outer bubblesort loop template < int i, int j > class IntBubbleSortLoop private : enum go = ( j <= i 2) ; s t a t i c inline void loop ( int data ) IntSwap < j, j +1 >::compareandswap ( data ) ; IntBubbleSortLoop < go? i : 0, go? \ ( j + 1 ) : 0 > : : loop ( data ) ; ; class IntBubbleSortLoop < 0, 0 > s t a t i c inline void loop ( int data ) ; Figure 16: Inner bubblesort loop 4.3 Conditional tests As stated before template metaprogramming is a Turing complete language. There are two things that we need to have in template meta programming to make it Turing complete. The first one is a construct that enables us to loop. 16

17 template< int i, int j > class IntSwap private : int temp ; s t a t i c inline void compareandswap ( int data ) i f ( data [ i ] > data [ j ] ) temp = data [ i ] ; data [ i ] = data [ j ] ; data [ j ] = temp ; ; Figure 17: Bubblesort swap This is fulfilled with the use of recursion as we have seen. Second we need a conditional test, this can also be achieved using templates. In figure 18 we see how we can do this. The specialization takes care of the false value of the condition and the instantiation takes care of the true value. In the simple example in 18 we only print the value of the conditional parameter, but we could have instead done some calculations or generated code. It is of course also possible to create a switch conditional using more template specializations. Figure 19 contains an example of this. Since it is possible to loop using recursion and create a conditional test using template specialization we see that C++ templates are indeed Turing complete. 17

18 template< bool Condition > class IF s t a t i c inline void EXEC( ) cout << " Statement is true" ; ; class IF < f a l s e > s t a t i c inline void EXEC( ) cout << " Statement is false" ; ; IF : : EXEC<boolean >; Figure 18: If test operation template< int case > class SWITCH s t a t i c inline void EXEC( ) cout << " SWITCH - default " ; ; class SWITCH< 1 > s t a t i c inline void EXEC( ) cout << " SWITCH - 1 " ; ; class SWITCH< 2 > s t a t i c inline void EXEC( ) cout << " SWITCH - 2 " ; ; SWITCH : : EXEC<Val >; Figure 19: Switch test operation 18

19 4.4 Expression templates Another important part of code generation with templates is expression templates. Thanks to expression templates expressions can be sent to functions as parameters, this technique was invented by Todd Veldhuizen in 1995 [3]. One field where expression templates can be used is calculation with vectors. The problem is that when the compiler computes with vectors it uses temporary vectors to split up a computation, this is shown using pseudo code in figure 20. Vector a, b, c, d ; a = ( b + c ) / d ; tempvector x, y ; x = b + c ; y = x / d ; a = y ; Figure 20: Psudeocode for vector calculation Because it is computation with vectors every row has to be computed in a loop, beside the need for temporary vectors. All this slows down the speed of the computation. To speed everything up the goal is to reduce the, in this case, three loops to one and have the algorithm inlined. In the example in figure 20 + and / has been overloaded, this makes the code easier to read but the performance is not that good. To make the code easy to read and fast like an inlined algorithm in one loop, expression templates is the answer. Though the overloading of operators still has to take place. An expression as b+c d can be seen as a tree with / as root and + and d as children. While d does not have any children + has b and c as children. When an expression can be seen as a tree it is obvious that nodes to build a tree has to be constructed. The code in figure 21 is a bit non descriptive so we will explain it. The class Uexp represent a unary expression with one child (T). The class Bexp of course then represents a binary expression with two children, left (L) and right (R). As stated before the + operator needs to be overloaded as can be seen in figure 22. The example code in figures 21 and 22 is far from complete but it shows the core of expression templates. That is that by using expressions as a parameter the compiler will build a function with the expression inline and a vector computation can be solved with a single pass without temporary vectors. 19

20 template < class T > class Uexp T t ;... template < class L, class R > class Bexp L l ; R r ;... Figure 21: Tree and node templates Uexp< Bexp< Vector, Vector >> operator + \ ( const Vector &v1, const Vector &v2 ) typedef Bexp< Vector, Vector > Exp ; return Uexp< Exp > (Exp( v1. begin ( ), v2. begin ( ) ) ) ; 5 Related techniques Figure 22: Generated code There are several techniques related to template metaprogramming. A full presentation of all of them is beyond this paper so we choose to present two that are widely used. Both can be used with the template metaprogramming techniques we have presented so far to create even more powerful software. 5.1 Mixin Mixin is a component based programming technique based on multiple inheritance and so called sibling calls. The idea is simple: we would like to specify an extension without pre-determining what exactly it can extend. This is equivalent to specifying a subclass while leaving its superclass as a parameter to be determined later. The benefit is that a single class can be used to express an incremental extension, valid for a variety of classes [14]. We can implement mixin using parameterized inheritance, that is we supply the class to be inherited from to the template implementationclass. A small code example can be seen in figure

21 The model of mixin can be seen as a rhomb with the constructed mixin class at the bottom. The mixin class inherits methods and interfaces rom interface and implementation classes, both of them are on the same level of the rhomb. These two inherits abstract methods from the base class. The base class is solely constructed of primitive abstract methods. The interface class is constructed of methods that in turn is constructed of primitive methods defined in the base class, a call to a method in a interface class can in turn call a number of primitive base methods. The implementation class on the other hand contains the implementation of the primitive methods. One method can have several different implementations, one that is faster, one that uses less memory and so on. In the mixin class the programmer choose which interface and methods to be used based on what is needed in the application. The connection between the base class and the mixin class can bee seen as a two way path, one path goes through the interface class and the other through the implementation class. Thanks to sibling calls the method in the implementation class is used when the method in the interface class is called, classes that are on different paths. Templates can of course be used in the classes to take away the type definition but templates can also be used to simulate the sibling calls in C++. The ideal is to have a giant library of interfaces and implementations and program by using them. template<class SuperClass> public class Mixin : public SuperClass / Mixin body / Figure 23: Implementation of mixin 5.2 Traits Support for internationalizing was one of the goals for the ANSI/ISO C++ Standard Library working group. During work on the internationalization several techniques were invented, one of which is the unexpectedly useful traits [16]. Traits radically simplifies the interface to class templates instantiable on native C++ types. An example of traits can be found in class numeric limits< T >, provided by the ANSI/ISO C++ Standard. The class contains information about the numerical properties of C++ types such as int and double. In ANSI C this is provided through constants such as INT MIN, INT MAX, FLT MIN, FLT MAX 21

22 (which represent the largest and smallest values for integers and doubles respectively). It is possible to use these constants in C++ but when using templates they are not useful since we can parameterize the type and therefore we do not know what constant to use. This problem is solved by using the numerical limits< T > class. The numeric limits< T > class provides a wealth of information about a numeric data type: its minimum and maximum values; how many binary and decimal digits can be considered accurate; whether it is signed; whether it is integer-valued; the radix of its representation (generally base 2); the machine epsilon; for floating point types, the range of exponents in base 2 and base 10; and details about rounding behavior [15]. Using all this information it is possible to write template numerical functions where the behavior depends of the type of number representation used. Traits can also be used as a technique for reducing the number of parameters to a given template. If a template has a large number of parameters the code often become more complex to read and to maintain. By using traits we create another template that we use instead of passing several different parameters to the first template. 6 Pros and cons with template metaprogramming 6.1 Pros An important thing is to know when to use template metaprogramming and when to not use it. First optimizations can be achieved by using metaprograms to calculate values at compile time instead of letting the run time program do it each time the program starts. Lookup tables can be created and loops with a predetermined number of iterations can be unrolled. Platform specific code can be isolated and a metaprogram can be used instead of macros to implement the code, also metaprograms can be used when a macro is not enough. An example where template metaprogramming has been used to achieve faster execution is the scientific computations library Blitz++ [12]. The goal of Blitz++ is to reach the speed of Fortran with C++ and by that get C++ in the focus of scientific computation. C++ has many features that is compelling to people that works with scientific computations but the performance could be better. Blitz++ has solved this by increasing performance using template metaprograms as an optimization technique. 22

23 6.2 Cons Since template metaprogramming depends on many advanced c++ language features it is not certain that the code will be portable across different compiler environments. Though more recent compilers have had more full featured support for templates. A big problem with template metaprogramming is that template compiler errors are not so user friendly most of the time. They can be several pages long and this information overload will make it difficult to track down the error. Another large problem with template metaprogramming is that since parts of the code is generated during the compilation time it becomes very hard to debug the resulting software. A subtle compiler bug could cause your program to calculate some values wrong or produce erroneous code. These kind of errors could be really hard to track down. This is of course is even harder if your vendor does not give you access to the compiler source. This is increased by the fact the the compiler cannot output any information during the instantiation of the templates. One could argue that template metaprogramming is simply just abuse of the C++ compiler environment and that it breaks the object oriented approach since it introduces a functional programming style that not all programmers are as familiar with as with the normal object oriented and procedural approaches. The threshold of learning template metaprogramming is also quite high. 23

24 7 Conclusion As we have seen there are many situations where the use of template metaprogramming can be really beneficial, since we can optimize software where we know that the program spends a lot of time. The problem though is that the developer must know when it is wise to make these optimizations and that is not always so easy so see. Though with good developers that can spot a problem that would benefit from template metaprogramming application speed could be improved. However for many problems the developer time is the most costly factor in development and the speed increase might not justify the increased complexity of the source code. A strict policy on where and when to use template metaprogramming could make these problems smaller but they would not disappear completely, but in certain situations it could be just the solution you are looking for. Even if you decide that template metaprogramming is not for you, at least your knowledge of what can and can not be done with the C++ programming language will be much greater. 24

25 References [1] Bjarne Stroustrup. An Overview of the C++ Programming language. Handbook of Object Technology. CRC Press [2] Todd L. Veldhuizen. C++ templates are Turing complete, tveldhui/papers/2003/turing.pdf [3] Todd L. Veldhuizen. Expression Templates. C++ Report Vol. 7 No. 5 (June 1995), pp [4] Todd L. Veldhuizen. Using C++ template metaprograms. C++ Report Vol. 7 No. 4 (May 1995), pp [5] David Abrahams and Carlos Pinto Coelho. Effects of metaprogramming style on compilation time speed/ [6] Microsft Developer Network. Templates vs. Macros. core templates vs.. macros.asp [7] SGI. Introduction to the Standard Template Library. introduction.html [8] Eric W. Weisstein et al. Series Expansion. From MathWorld A Wolfram Web Resource. [9] Eric W. Weisstein. Fast Fourier Transform. From MathWorld A Wolfram Web Resource. [10] Aleksey Gurtovoy. David Abrahams and Emily Winch. The Boost MPL library [11] Free Software Foundation. Using the GNU Compiler Collection (GCC). [12] Blitz++ homepage. Goals of the Blitz++ library [13] Erwin Unruh. Temple Metaprogrammierung. [14] Yannis Smaragdakis, Don Batory. Mixin-Based Programming in C++. Proceedings of the Second International Symposium on Generative and Component-Based Software Engineering-Revised Papers. 2001, pp [15] Todd Veldhuizen. Using C++ Trait Classes for Scientific Computing [16] Nathan C. Myers. Traits: a new and useful template technique. C++ Report Vol. 7 No. 5 (June 1995). 25

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

Semantics of C++ Hauptseminar im Wintersemester 2009/10 Templates

Semantics of C++ Hauptseminar im Wintersemester 2009/10 Templates Semantics of C++ Hauptseminar im Wintersemester 2009/10 Templates Sebastian Wild Technische Universität München 11.01.2010 Abstract In this work we will discuss about templates in C++, especially their

More information

COMP322 - Introduction to C++ Lecture 01 - Introduction

COMP322 - Introduction to C++ Lecture 01 - Introduction COMP322 - Introduction to C++ Lecture 01 - Introduction Robert D. Vincent School of Computer Science 6 January 2010 What this course is Crash course in C++ Only 14 lectures Single-credit course What this

More information

On the correctness of template metaprograms

On the correctness of template metaprograms Proceedings of the 7 th International Conference on Applied Informatics Eger, Hungary, January 28 31, 2007 Vol 2 pp 301 308 On the correctness of template metaprograms Ádám Sipos, István Zólyomi, Zoltán

More information

QUIZ. What are 3 differences between C and C++ const variables?

QUIZ. What are 3 differences between C and C++ const variables? QUIZ What are 3 differences between C and C++ const variables? Solution QUIZ Source: http://stackoverflow.com/questions/17349387/scope-of-macros-in-c Solution The C/C++ preprocessor substitutes mechanically,

More information

CS 376b Computer Vision

CS 376b Computer Vision CS 376b Computer Vision 09 / 25 / 2014 Instructor: Michael Eckmann Today s Topics Questions? / Comments? Enhancing images / masks Cross correlation Convolution C++ Cross-correlation Cross-correlation involves

More information

Introducing C++ to Java Programmers

Introducing C++ to Java Programmers Introducing C++ to Java Programmers by Kip Irvine updated 2/27/2003 1 Philosophy of C++ Bjarne Stroustrup invented C++ in the early 1980's at Bell Laboratories First called "C with classes" Design Goals:

More information

Chapter 1 Getting Started

Chapter 1 Getting Started Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different

More information

6.096 Introduction to C++ January (IAP) 2009

6.096 Introduction to C++ January (IAP) 2009 MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. Welcome to 6.096 Lecture

More information

1 Introduction. Martin Böhme Bodo Manthey

1 Introduction. Martin Böhme Bodo Manthey THE COMPUTATIONAL POWER OF COMPILING C++ Martin Böhme Bodo Manthey Abstract Using a C++ compiler, any partial recursive function can be computed at compile time. We show this by using the C++ template

More information

377 Student Guide to C++

377 Student Guide to C++ 377 Student Guide to C++ c Mark Corner January 21, 2004 1 Introduction In this course you will be using the C++ language to complete several programming assignments. Up to this point we have only provided

More information

Scientific Computing

Scientific Computing Scientific Computing Martin Lotz School of Mathematics The University of Manchester Lecture 1, September 22, 2014 Outline Course Overview Programming Basics The C++ Programming Language Outline Course

More information

These are notes for the third lecture; if statements and loops.

These are notes for the third lecture; if statements and loops. These are notes for the third lecture; if statements and loops. 1 Yeah, this is going to be the second slide in a lot of lectures. 2 - Dominant language for desktop application development - Most modern

More information

AN OVERVIEW OF C++ 1

AN OVERVIEW OF C++ 1 AN OVERVIEW OF C++ 1 OBJECTIVES Introduction What is object-oriented programming? Two versions of C++ C++ console I/O C++ comments Classes: A first look Some differences between C and C++ Introducing function

More information

CE221 Programming in C++ Part 1 Introduction

CE221 Programming in C++ Part 1 Introduction CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab

More information

QUIZ. What is wrong with this code that uses default arguments?

QUIZ. What is wrong with this code that uses default arguments? QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code

More information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

Functions, Pointers, and the Basics of C++ Classes

Functions, Pointers, and the Basics of C++ Classes Functions, Pointers, and the Basics of C++ Classes William E. Skeith III Functions in C++ Vocabulary You should be familiar with all of the following terms already, but if not, you will be after today.

More information

CS93SI Handout 04 Spring 2006 Apr Review Answers

CS93SI Handout 04 Spring 2006 Apr Review Answers CS93SI Handout 04 Spring 2006 Apr 6 2006 Review Answers I promised answers to these questions, so here they are. I'll probably readdress the most important of these over and over again, so it's not terribly

More information

To become familiar with array manipulation, searching, and sorting.

To become familiar with array manipulation, searching, and sorting. ELECTRICAL AND COMPUTER ENGINEERING 06-88-211: COMPUTER AIDED ANALYSIS LABORATORY EXPERIMENT #2: INTRODUCTION TO ARRAYS SID: OBJECTIVE: SECTIONS: Total Mark (out of 20): To become familiar with array manipulation,

More information

Programming in C and C++

Programming in C and C++ Programming in C and C++ 5. C++: Overloading, Namespaces, and Classes Dr. Neel Krishnaswami University of Cambridge (based on notes from and with thanks to Anil Madhavapeddy, Alan Mycroft, Alastair Beresford

More information

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite

More information

Announcements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy

Announcements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy CSCI 334: Principles of Programming Languages Lecture 18: C/C++ Homework help session will be tomorrow from 7-9pm in Schow 030A instead of on Thursday. Instructor: Dan Barowy HW6 and HW7 solutions We only

More information

UNIT TESTING OF C++ TEMPLATE METAPROGRAMS

UNIT TESTING OF C++ TEMPLATE METAPROGRAMS STUDIA UNIV. BABEŞ BOLYAI, INFORMATICA, Volume LV, Number 1, 2010 UNIT TESTING OF C++ TEMPLATE METAPROGRAMS ÁBEL SINKOVICS Abstract. Unit testing, a method for verifying a piece of software, is a widely

More information

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012 MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012 Instructor: K. S. Booth Time: 70 minutes (one hour ten minutes)

More information

How to approach a computational problem

How to approach a computational problem How to approach a computational problem A lot of people find computer programming difficult, especially when they first get started with it. Sometimes the problems are problems specifically related to

More information

CSE 303: Concepts and Tools for Software Development

CSE 303: Concepts and Tools for Software Development CSE 303: Concepts and Tools for Software Development Hal Perkins Autumn 2008 Lecture 24 Introduction to C++ CSE303 Autumn 2008, Lecture 24 1 C++ C++ is an enormous language: All of C Classes and objects

More information

The Design Process. General Development Issues. C/C++ and OO Rules of Thumb. Home

The Design Process. General Development Issues. C/C++ and OO Rules of Thumb. Home A l l e n I. H o l u b & A s s o c i a t e s Home C/C++ and OO Rules of Thumb The following list is essentially the table of contents for my book Enough Rope to Shoot Yourself in the Foot (McGraw-Hill,

More information

C++ For C Programmers Week 1 Part 1

C++ For C Programmers Week 1 Part 1 C++ For C Programmers Week 1 Part 1 Overview and Course Organization C++ as a Better C Problem 1 Convert C Code to be posted Course work 1. Homework 3 Programs to Code 2. One Final- closed book C++ is

More information

A brief introduction to C++

A brief introduction to C++ A brief introduction to C++ Rupert Nash r.nash@epcc.ed.ac.uk 13 June 2018 1 References Bjarne Stroustrup, Programming: Principles and Practice Using C++ (2nd Ed.). Assumes very little but it s long Bjarne

More information

C++ C and C++ C++ fundamental types. C++ enumeration. To quote Bjarne Stroustrup: 5. Overloading Namespaces Classes

C++ C and C++ C++ fundamental types. C++ enumeration. To quote Bjarne Stroustrup: 5. Overloading Namespaces Classes C++ C and C++ 5. Overloading Namespaces Classes Alastair R. Beresford University of Cambridge Lent Term 2007 To quote Bjarne Stroustrup: C++ is a general-purpose programming language with a bias towards

More information

Expression Templates (Todd Veldhuizen)

Expression Templates (Todd Veldhuizen) 1 of 8 23-12-2004 12:01 You may also be interested in: Source code for the dvec example in this paper: dexpr.h dvec.h dvec.cpp Template Metaprograms C++ Templates as Partial Evaluation [PS] [HTML] [bibtex]

More information

G52CPP C++ Programming Lecture 9

G52CPP C++ Programming Lecture 9 G52CPP C++ Programming Lecture 9 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture const Constants, including pointers The C pre-processor And macros Compiling and linking And

More information

Subroutines. Subroutine. Subroutine design. Control abstraction. If a subroutine does not fit on the screen, it is too long

Subroutines. Subroutine. Subroutine design. Control abstraction. If a subroutine does not fit on the screen, it is too long Subroutines Subroutine = procedure (statement) - no return value - side effects function (expression) - return value - (no side effects in some languages) Subroutine Control abstraction Subroutine design

More information

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms AUTO POINTER (AUTO_PTR) //Example showing a bad situation with naked pointers void MyFunction()

More information

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak! //Example showing a bad situation with naked pointers CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms void MyFunction() MyClass* ptr( new

More information

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures The main body and cout Agenda 1 Fundamental data types Declarations and definitions Control structures References, pass-by-value vs pass-by-references The main body and cout 2 C++ IS AN OO EXTENSION OF

More information

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING 1. Object Oriented Programming Paradigms 2. Comparison of Programming Paradigms 3. Basic Object Oriented Programming

More information

Computer Components. Software{ User Programs. Operating System. Hardware

Computer Components. Software{ User Programs. Operating System. Hardware Computer Components Software{ User Programs Operating System Hardware What are Programs? Programs provide instructions for computers Similar to giving directions to a person who is trying to get from point

More information

C++ Programming Lecture 7 Software Engineering Group

C++ Programming Lecture 7 Software Engineering Group C++ Programming Lecture 7 Software Engineering Group Philipp D. Schubert Contents 1. Template metaprogramming 2. Variadic template arguments 3. Smart pointer Template metaprogramming Template metaprogramming

More information

Programming at Compile Time. Rainer Grimm Training, Coaching, and Technology Consulting

Programming at Compile Time. Rainer Grimm Training, Coaching, and Technology Consulting Programming at Compile Time Rainer Grimm Training, Coaching, and Technology Consulting www.modernescpp.de Overview Constant expressions Type-traits library Template metaprogramming Template Metaprogramming

More information

Programming at Compile Time. Rainer Grimm Training, Coaching, and Technology Consulting

Programming at Compile Time. Rainer Grimm Training, Coaching, and Technology Consulting Programming at Compile Time Rainer Grimm Training, Coaching, and Technology Consulting www.modernescpp.de Overview Constant expressions Type-traits library Template metaprogramming Template Metaprogramming

More information

by Marina Cholakyan, Hyduke Noshadi, Sepehr Sahba and Young Cha

by Marina Cholakyan, Hyduke Noshadi, Sepehr Sahba and Young Cha CS 111 Scribe Notes for 4/11/05 by Marina Cholakyan, Hyduke Noshadi, Sepehr Sahba and Young Cha Processes What is a process? A process is a running instance of a program. The Web browser you're using to

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010 CSE 374 Programming Concepts & Tools Hal Perkins Spring 2010 Lecture 19 Introduction ti to C++ C++ C++ is an enormous language: g All of C Classes and objects (kind of like Java, some crucial differences)

More information

III. Classes (Chap. 3)

III. Classes (Chap. 3) III. Classes III-1 III. Classes (Chap. 3) As we have seen, C++ data types can be classified as: Fundamental (or simple or scalar): A data object of one of these types is a single object. int, double, char,

More information

5. Control Statements

5. Control Statements 5. Control Statements This section of the course will introduce you to the major control statements in C++. These control statements are used to specify the branching in an algorithm/recipe. Control statements

More information

An introduction to C++ template programming

An introduction to C++ template programming An introduction to C++ template programming Hayo Thielecke University of Birmingham http://www.cs.bham.ac.uk/~hxt March 2015 Templates and parametric polymorphism Template parameters Member functions of

More information

PIC 10A Objects/Classes

PIC 10A Objects/Classes PIC 10A Objects/Classes Ernest Ryu UCLA Mathematics Last edited: November 13, 2017 User-defined types In C++, we can define our own custom types. Object is synonymous to variable, and class is synonymous

More information

G52CPP C++ Programming Lecture 20

G52CPP C++ Programming Lecture 20 G52CPP C++ Programming Lecture 20 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Wrapping up Slicing Problem Smart pointers More C++ things Exams 2 The slicing problem 3 Objects are not

More information

C++ for Java Programmers

C++ for Java Programmers Basics all Finished! Everything we have covered so far: Lecture 5 Operators Variables Arrays Null Terminated Strings Structs Functions 1 2 45 mins of pure fun Introduction Today: Pointers Pointers Even

More information

Chapter 2 Basic Elements of C++

Chapter 2 Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2-1 Chapter 2 Basic Elements of C++ At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion

More information

C++ Programming Lecture 6 Software Engineering Group

C++ Programming Lecture 6 Software Engineering Group C++ Programming Lecture 6 Software Engineering Group Philipp D. Schubert Dynamic memory allocation Quick reminder: Do not confuse between the (de)allocation operators! void* operator new ( std::size_t

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++ CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 19 Introduction to C++ C++ C++ is an enormous language: All of C Classes and objects (kind of like Java, some crucial differences) Many

More information

Chapter - 9 Variable Scope and Functions. Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 1

Chapter - 9 Variable Scope and Functions. Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 1 Chapter - 9 Variable Scope and Functions Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 1 Variable Scope and Class Variables are defined by two attributes: Scope The area where a

More information

Chapter 2. Procedural Programming

Chapter 2. Procedural Programming Chapter 2 Procedural Programming 2: Preview Basic concepts that are similar in both Java and C++, including: standard data types control structures I/O functions Dynamic memory management, and some basic

More information

QUIZ. Source:

QUIZ. Source: QUIZ Source: http://stackoverflow.com/questions/17349387/scope-of-macros-in-c Ch. 4: Data Abstraction The only way to get massive increases in productivity is to leverage off other people s code. That

More information

Figure 1 Common Sub Expression Optimization Example

Figure 1 Common Sub Expression Optimization Example General Code Optimization Techniques Wesley Myers wesley.y.myers@gmail.com Introduction General Code Optimization Techniques Normally, programmers do not always think of hand optimizing code. Most programmers

More information

Software Development with C++ Templates

Software Development with C++ Templates Software Development with C++ Templates Lab Submission 1 Exercises should be solved in groups of two. However, with approval from the lecturer, exercises may also be solved alone or in groups of three.

More information

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

More information

11. Generic Programming and Design Patterns. 8. Juli 2011

11. Generic Programming and Design Patterns. 8. Juli 2011 8. Juli 2011 Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 1 of 26 Outline Recapitulation Template Programming An Overview over the STL Design Patterns (skipped) Evaluation/feedback

More information

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

COMP322 - Introduction to C++ Lecture 02 - Basics of C++ COMP322 - Introduction to C++ Lecture 02 - Basics of C++ School of Computer Science 16 January 2012 C++ basics - Arithmetic operators Where possible, C++ will automatically convert among the basic types.

More information

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26 COSC 2P95 Procedural Abstraction Week 3 Brock University Brock University (Week 3) Procedural Abstraction 1 / 26 Procedural Abstraction We ve already discussed how to arrange complex sets of actions (e.g.

More information

C++ for numerical computing

C++ for numerical computing C++ for numerical computing Rupert Nash r.nash@epcc.ed.ac.uk 13 June 2018 1 Outline Introduction Containers Iterators Object oriented C++ 2 What this is not! Writing efficient software, more than anything,

More information

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter

More information

Fundamentals of Programming Languages

Fundamentals of Programming Languages Fundamentals of Programming Languages 1. DEFINITIONS... 2 2. BUILT-IN TYPES AND PRIMITIVE TYPES... 3 TYPE COMPATIBILITY... 9 GENERIC TYPES... 14 MONOMORPHIC VERSUS POLYMORPHIC... 16 TYPE IMPLEMENTATION

More information

6. Pointers, Structs, and Arrays. 1. Juli 2011

6. Pointers, Structs, and Arrays. 1. Juli 2011 1. Juli 2011 Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 1 of 50 Outline Recapitulation Pointers Dynamic Memory Allocation Structs Arrays Bubble Sort Strings Einführung

More information

use static size for this buffer

use static size for this buffer Software Design (C++) 4. Templates and standard library (STL) Juha Vihavainen University of Helsinki Overview Introduction to templates (generics) std::vector again templates: specialization by code generation

More information

Machine Language Instructions Introduction. Instructions Words of a language understood by machine. Instruction set Vocabulary of the machine

Machine Language Instructions Introduction. Instructions Words of a language understood by machine. Instruction set Vocabulary of the machine Machine Language Instructions Introduction Instructions Words of a language understood by machine Instruction set Vocabulary of the machine Current goal: to relate a high level language to instruction

More information

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE? 1. Describe History of C++? The C++ programming language has a history going back to 1979, when Bjarne Stroustrup was doing work for his Ph.D. thesis. One of the languages Stroustrup had the opportunity

More information

Comp 11 Lectures. Mike Shah. June 26, Tufts University. Mike Shah (Tufts University) Comp 11 Lectures June 26, / 57

Comp 11 Lectures. Mike Shah. June 26, Tufts University. Mike Shah (Tufts University) Comp 11 Lectures June 26, / 57 Comp 11 Lectures Mike Shah Tufts University June 26, 2017 Mike Shah (Tufts University) Comp 11 Lectures June 26, 2017 1 / 57 Please do not distribute or host these slides without prior permission. Mike

More information

Where do we go from here?

Where do we go from here? Where do we go from here? C++ classes and objects, with all the moving parts visible operator overloading templates, STL, standards, Java components, collections, generics language and performance comparisons

More information

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED Outline - Function Definitions - Function Prototypes - Data

More information

C++ Basics. Brian A. Malloy. References Data Expressions Control Structures Functions. Slide 1 of 24. Go Back. Full Screen. Quit.

C++ Basics. Brian A. Malloy. References Data Expressions Control Structures Functions. Slide 1 of 24. Go Back. Full Screen. Quit. C++ Basics January 19, 2012 Brian A. Malloy Slide 1 of 24 1. Many find Deitel quintessentially readable; most find Stroustrup inscrutable and overbearing: Slide 2 of 24 1.1. Meyers Texts Two excellent

More information

C++ Important Questions with Answers

C++ Important Questions with Answers 1. Name the operators that cannot be overloaded. sizeof,.,.*,.->, ::,? 2. What is inheritance? Inheritance is property such that a parent (or super) class passes the characteristics of itself to children

More information

Introduction to C++ Introduction to C++ 1

Introduction to C++ Introduction to C++ 1 1 What Is C++? (Mostly) an extension of C to include: Classes Templates Inheritance and Multiple Inheritance Function and Operator Overloading New (and better) Standard Library References and Reference

More information

CSCE 314 Programming Languages. Type System

CSCE 314 Programming Languages. Type System CSCE 314 Programming Languages Type System Dr. Hyunyoung Lee 1 Names Names refer to different kinds of entities in programs, such as variables, functions, classes, templates, modules,.... Names can be

More information

Interview Questions of C++

Interview Questions of C++ Interview Questions of C++ Q-1 What is the full form of OOPS? Ans: Object Oriented Programming System. Q-2 What is a class? Ans: Class is a blue print which reflects the entities attributes and actions.

More information

Towards Automatic Partial Evaluation for the C++ Language. Robert Anisko

Towards Automatic Partial Evaluation for the C++ Language. Robert Anisko Towards Automatic Partial Evaluation for the C++ Language Robert Anisko May 27, 2002 Partial evaluation is a high-level optimization technique that, given a program text and some of its input, generates

More information

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value Paytm Programming Sample paper: 1) A copy constructor is called a. when an object is returned by value b. when an object is passed by value as an argument c. when compiler generates a temporary object

More information

CSE030 Fall 2012 Final Exam Friday, December 14, PM

CSE030 Fall 2012 Final Exam Friday, December 14, PM CSE030 Fall 2012 Final Exam Friday, December 14, 2012 3-6PM Write your name here and at the top of each page! Name: Select your lab session: Tuesdays Thursdays Paper. If you have any questions or need

More information

CSCI-1200 Data Structures Spring 2018 Lecture 14 Associative Containers (Maps), Part 1 (and Problem Solving Too)

CSCI-1200 Data Structures Spring 2018 Lecture 14 Associative Containers (Maps), Part 1 (and Problem Solving Too) CSCI-1200 Data Structures Spring 2018 Lecture 14 Associative Containers (Maps), Part 1 (and Problem Solving Too) HW6 NOTE: Do not use the STL map or STL pair for HW6. (It s okay to use them for the contest.)

More information

COMP 181. Agenda. Midterm topics. Today: type checking. Purpose of types. Type errors. Type checking

COMP 181. Agenda. Midterm topics. Today: type checking. Purpose of types. Type errors. Type checking Agenda COMP 181 Type checking October 21, 2009 Next week OOPSLA: Object-oriented Programming Systems Languages and Applications One of the top PL conferences Monday (Oct 26 th ) In-class midterm Review

More information

Instantiation of Template class

Instantiation of Template class Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double

More information

CSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion

CSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion CSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion Review from Lectures 5 & 6 Arrays and pointers, Pointer arithmetic and dereferencing, Types of memory ( automatic, static,

More information

C++ Data Types. 1 Simple C++ Data Types 2. 3 Numeric Types Integers (whole numbers) Decimal Numbers... 5

C++ Data Types. 1 Simple C++ Data Types 2. 3 Numeric Types Integers (whole numbers) Decimal Numbers... 5 C++ Data Types Contents 1 Simple C++ Data Types 2 2 Quick Note About Representations 3 3 Numeric Types 4 3.1 Integers (whole numbers)............................................ 4 3.2 Decimal Numbers.................................................

More information

1 Lecture 5: Advanced Data Structures

1 Lecture 5: Advanced Data Structures L5 June 14, 2017 1 Lecture 5: Advanced Data Structures CSCI 1360E: Foundations for Informatics and Analytics 1.1 Overview and Objectives We ve covered list, tuples, sets, and dictionaries. These are the

More information

So on the survey, someone mentioned they wanted to work on heaps, and someone else mentioned they wanted to work on balanced binary search trees.

So on the survey, someone mentioned they wanted to work on heaps, and someone else mentioned they wanted to work on balanced binary search trees. So on the survey, someone mentioned they wanted to work on heaps, and someone else mentioned they wanted to work on balanced binary search trees. According to the 161 schedule, heaps were last week, hashing

More information

Organization of Programming Languages CS 3200/5200N. Lecture 09

Organization of Programming Languages CS 3200/5200N. Lecture 09 Organization of Programming Languages CS 3200/5200N Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio.edu Control Flow Control flow = the flow of control, or execution

More information

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency Introduction Fundamentals Declaring arrays Indexing arrays Initializing arrays Arrays and functions Multidimensional arrays Sorting and algorithm efficiency An array is a sequence of values of the same

More information

C++ for Everyone, 2e, Cay Horstmann, Copyright 2012 John Wiley and Sons, Inc. All rights reserved. Using a Debugger WE5.

C++ for Everyone, 2e, Cay Horstmann, Copyright 2012 John Wiley and Sons, Inc. All rights reserved. Using a Debugger WE5. Using a Debugger WE5 W o r k E D E x a m p l e 5.2 Using a Debugger As you have undoubtedly realized by now, computer programs rarely run perfectly the first time. At times, it can be quite frustrating

More information

Software Design and Analysis for Engineers

Software Design and Analysis for Engineers Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 1 Date:

More information

Compilers. Prerequisites

Compilers. Prerequisites Compilers Prerequisites Data structures & algorithms Linked lists, dictionaries, trees, hash tables Formal languages & automata Regular expressions, finite automata, context-free grammars Machine organization

More information

Procedures, Parameters, Values and Variables. Steven R. Bagley

Procedures, Parameters, Values and Variables. Steven R. Bagley Procedures, Parameters, Values and Variables Steven R. Bagley Recap A Program is a sequence of statements (instructions) Statements executed one-by-one in order Unless it is changed by the programmer e.g.

More information

Chapter 15 - C++ As A "Better C"

Chapter 15 - C++ As A Better C Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference

More information

Symbol Tables. ASU Textbook Chapter 7.6, 6.5 and 6.3. Tsan-sheng Hsu.

Symbol Tables. ASU Textbook Chapter 7.6, 6.5 and 6.3. Tsan-sheng Hsu. Symbol Tables ASU Textbook Chapter 7.6, 6.5 and 6.3 Tsan-sheng Hsu tshsu@iis.sinica.edu.tw http://www.iis.sinica.edu.tw/~tshsu 1 Definitions Symbol table: A data structure used by a compiler to keep track

More information

/633 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Sorting lower bound and Linear-time sorting Date: 9/19/17

/633 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Sorting lower bound and Linear-time sorting Date: 9/19/17 601.433/633 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Sorting lower bound and Linear-time sorting Date: 9/19/17 5.1 Introduction You should all know a few ways of sorting in O(n log n)

More information

Lecture 2, September 4

Lecture 2, September 4 Lecture 2, September 4 Intro to C/C++ Instructor: Prashant Shenoy, TA: Shashi Singh 1 Introduction C++ is an object-oriented language and is one of the most frequently used languages for development due

More information

Unit 1 : Principles of object oriented programming

Unit 1 : Principles of object oriented programming Unit 1 : Principles of object oriented programming Difference Between Procedure Oriented Programming (POP) & Object Oriented Programming (OOP) Divided Into Importance Procedure Oriented Programming In

More information