GridKa School 2013: Effective Analysis C++ Templates

Similar documents
GridKa School 2013: Effective Analysis C++ Standard Template Library

Cpt S 122 Data Structures. Templates

COEN244: Class & function templates

10. Functions (Part 2)

Other C++11/14 features

Introduction to Core C++

Topics. bool and string types input/output library functions comments memory allocation templates classes

Object Oriented Design

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

template<typename T> cout << "The value is << value << endl; } void printdata(t value){

C The new standard

Object-Oriented Programming for Scientific Computing

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

CS11 Advanced C++ Fall Lecture 7

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

Distributed and Parallel Systems Group University of Innsbruck. Simone Pellegrini, Radu Prodan and Thomas Fahringer

Tokens, Expressions and Control Structures

AN OVERVIEW OF C++ 1

Templates. Zoltán Porkoláb: C++11/14 1

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.

SFU CMPT Topic: Class Templates

Object-Oriented Programming for Scientific Computing

TDDD38 - Advanced programming in C++

1. The term STL stands for?

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy

Variables. Data Types.

Bruce Merry. IOI Training Dec 2013

COSC 320 Exam 2 Key Spring Part 1: Hash Functions

Templates and Vectors

COMP 2355 Introduction to Systems Programming

Basic Templates Intro

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works

Introduction to Standard C++

Overload Resolution. Ansel Sermersheim & Barbara Geller ACCU / C++ June 2018

EL2310 Scientific Programming

Outline. Variables Automatic type inference. Generic programming. Generic programming. Templates Template compilation

Introduction to C++ Systems Programming

Introduction to C++ Friends, Nesting, Static Members, and Templates Topic #7

The Cut and Thrust of CUDA

Generic Programming. Akim D le Étienne Renault Roland Levillain

The following is an excerpt from Scott Meyers new book, Effective C++, Third Edition: 55 Specific Ways to Improve Your Programs and Designs.

COMP6771 Advanced C++ Programming

Creating Templates and Implementing Smart Pointers CS193D 2/27/06

G52CPP C++ Programming Lecture 18

! Operators such as =, +, <, can be defined to. ! The function names are operator followed by the. ! Otherwise they are like normal member functions:

CS

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

Function Templates. Consider the following function:

Comp151. Function Templates & Class Templates

Programming in C++: Assignment Week 8

7 TEMPLATES AND STL. 7.1 Function Templates

A brief introduction to C++

Elevate your Code to Modern C++ with Automated Tooling. Peter Sommerlad

ME240 Computation for Mechanical Engineering. Lecture 4. C++ Data Types

I m sure you have been annoyed at least once by having to type out types like this:

Templates. Giuseppe Lipari Scuola Superiore Sant Anna Pisa. June 8, 2009

Advanced C++ 4/13/2017. The user. Types of users. Const correctness. Const declaration. This pointer and const.

C++ Functions. Procedural-based Programming. what s a functions

Software Design Tidbits. Bálint Joó, Scientific Computing Group Jefferson Lab

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

Introduction to Programming Using Java (98-388)

Advanced C++ Programming Workshop (With C++11, C++14, C++17) & Design Patterns

Inheritance and Overloading. Week 11

Overload Resolution. Ansel Sermersheim & Barbara Geller Amsterdam C++ Group March 2019

by Pearson Education, Inc. All Rights Reserved. 2

Design Patterns in C++

CS3157: Advanced Programming. Outline

CPSC 427: Object-Oriented Programming

Homework 5. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011

C++ Primer for CS175

Lecture 2 Polymorphism, Traits, Policies, and Inheritance

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

CSI33 Data Structures

use static size for this buffer

Part X. Advanced C ++

Improve your C++! John Richardson. Lab Study Meeting 2013

Introduction to metaprogramming. Nicolas Burrus

III. Classes (Chap. 3)

Introduction to Move Semantics in C++ C and C

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

A Fast Review of C Essentials Part I

Exercise 1.1 Hello world

C++ TEMPLATES. Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type.

6.096 Introduction to C++ January (IAP) 2009

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

C++ Programming Fundamentals

CS 376b Computer Vision

Lecture 8. Xiaoguang Wang. February 13th, 2014 STAT 598W. (STAT 598W) Lecture 8 1 / 47

OBJECT ORIENTED PROGRAMMING USING C++

C++: Overview and Features

! Search: find a given target item in an array, ! Linear Search: Very simple search method: ! Operators such as =, +, <, and others can be

Lab 1: First Steps in C++ - Eclipse

C++_ MARKS 40 MIN

CHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object

Design Patterns in C++

An introduction to. Templates. Generic Programming. Good old C. Metaprogramming 4/13/2017

Lecture on pointers, references, and arrays and vectors

Advanced C++ Topics. Alexander Warg, 2017

Transcription:

GridKa School 2013: Effective Analysis C++ Templates Introduction Jörg Meyer, Steinbuch Centre for Computing, Scientific Data Management KIT University of the State of Baden-Wuerttemberg and National Research Center of the Helmholtz Association www.kit.edu

What are templates? Why use them? Many algorithms are independent of data types e.g. sorting: algorithm does not care what to sort, as long as it knows how to compare things Template: allows to write code (functions, classes) for generic type Code gets instantiated for actual type at compile time (static polymorphism) no overhead at runtime no virtual calls, no common base class needed no conversion from void* no issues like with MACROS Meta programming: very powerful, STL full of templates 2

Why not to use templates? (not really ) error messages sometimes hard to read debugging cumbersome error.cpp:8:13: error: empty character constant error.cpp:9:17: error: empty character constant error.cpp: In instantiation of T foo(const T&) [with T = std::vector<std::basic_string<char> >] : error.cpp:15:8: required from here error.cpp:8:3: error: no matching function for call to std::vector<std::basic_string<char> >::begin(int) const error.cpp:8:3: note: candidates are: In file included from /usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/vector:65:0, from error.cpp:1: /usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/bits/stl_vector.h:518:7: note: std::vector<_tp, _Alloc>::iterator std::vector<_tp, _Alloc>::begin() [with _Tp = std::basic_string<char>; _Alloc = std::allocator<std::basic_string<char> >; std::vector<_tp, _Alloc>::iterator = gnu_cxx:: normal_iterator<std::basic_string<char>*, std::vector<std::basic_string<char> > >; typename std::_vector_base<_tp, _Alloc>::pointer = std::basic_string<char>*] /usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/bits/stl_vector.h:518:7: note: candidate expects 0 arguments, 1 provided /usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/bits/stl_vector.h:527:7: note: std::vector<_tp, _Alloc>::const_iterator std::vector<_tp, _Alloc>::begin() const [with _Tp = std::basic_string<char>; _Alloc = std::allocator<std::basic_string<char> >; std::vector<_tp, _Alloc>::const_iterator = gnu_cxx:: normal_iterator<const std::basic_string<char>*, std::vector<std::basic_string<char> > >; typename gnu_cxx:: alloc_traits<typename std::_vector_base<_tp, _Alloc>::_Tp_alloc_type>::const_pointer = const std::basic_string<char>*] /usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/bits/stl_vector.h:527:7: note: candidate expects 0 arguments, 1 provided error.cpp:9:3: error: no matching function for call to std::basic_string<char>::length(int) const error.cpp:9:3: note: candidate is: In file included from /usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/string:54:0, from error.cpp:2: /usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/bits/basic_string.h:718:7: note: std::basic_string<_chart, _Traits, _Alloc>::size_type std::basic_string<_chart, _Traits, _Alloc>::length() const [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>; std::basic_string<_chart, _Traits, _Alloc>::size_type = long unsigned int] /usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/bits/basic_string.h:718:7: note: candidate expects 0 arguments, 1 provided 3

Function templates a+b: template <typename T> T sum(t const& a, T const& b) { return a+b; int main() { int i=2; int j=4; string s1 = "Hello "; string s2 = "World"; cout<<sum(i,j)<<endl; cout<<sum(s1,s2)<<endl; int sum(int const& a, int const& b) { return a+b; string sum(string const& a, string const& b) { return a+b; 4

Function templates (conversion) no automatic type conversion template <typename T> T sum(t const& a, T const& b) { return a+b; int main() { int i=2; double d=4.; cout<<sum(i,d)<<endl; //compile-time error cout<<sum<double>(i,d)<<endl; //ok 5

Function templates (C++11) new keyword: decltype template <typename T1, typename T2> decltype(a+b) sum(t1 const& a, T2 const& b) { return a+b; int main() { int i=2; double d=4.; cout<<sum(i,d)<<endl; //ok 6

Function templates (overloading) template function can be overloaded like normal functions: template <typename T> T sum(t const& a, T const& b) { return a+b; char const* sum(char const* a, char const* b) { cout<< char <<endl; return (string(a)+string(b)).c_str(); int main() { cout<<sum( Hello, World )<<endl; 7

Function templates (summary) function template: set of functions for different template types function template instantiated if being used with certain template argument template parameters can be deduced or explicitly being qualified function templates can be overloaded 8

Class templates parametrize classes by templates: template <typename T> class histogram { ; std::vector<t> bins; //content of histogram double xmin,xmax; //range for x-axis public: typedef T value_type; int Fill(double value, T weight=1) { unsigned int bin=findbin(value); bins[bin]+=weight; return bin; 9

Class templates (usage) usage of class templates already known from STL classes like vector histogram<float> H1F; H1F.Fill(3.14); histogram<double> H1D; double d = H1D.GetBinContent(2); 10

Class templates (class type) class type: histogram<t> template <typename T> class histogram { histogram(histogram<t> const&); // copy c tor histogram<t>& operator=(histogram<t> const&); //assignment ; 11 template <typename T> histogram<t>& histogram<t>::operator=(histogram<t> const&) {

Class templates (specialization) special implementation for T=big_number (partial specialization possible) class big_number; //user-defined class for huge numbers class big_number_allocator; //allocates space for big_number template <> class histogram<big_number> { std::vector<big_number,big_number_allocator> bins; //content of histogram ; double xmin,xmax; //range for x-axis public: typedef big_number value_type; int Fill(double value, big_number weight=1) 12

Class templates (default template argument) default type for second template argument: template <typename T, typename Alloc = allocator<t> > class histogram { ; std::vector<t,alloc> bins; //content of histogram histogram<int> hi; histogram<big_number,big_number_allocator> hbn; 13

Class template (summary) class template: implemented with some type parameters left open usage: vector<int> -> instantiates vector for type int class templates can be (partially) specialized class template arguments can have default values member functions of class templates get only instantiated if they are being used 14

Nontype templates value as template parameter #include<iostream> #include<vector> using namespace std; template <typename T, unsigned DIM> class vec { private: vector<t> v; public: vec() : v(dim,0) {; T& operator[](unsigned n) {return v[n]; T const& operator[](unsigned n) const {return v[n]; ; 15

Nontype templates // scalar product template<typename T, unsigned DIM> T operator*(vec<t,dim> const& a, vec<t,dim> const& b) { T ret = T(); for (int i=0;i!=dim;++i) ret+=a[i]*b[i]; return ret; int main() { vec<double,3> v1; v1[0]=1.; v1[1]=4.; v1[2]=2.; vec<double,3> v2; v2[0]=-1.; v2[1]=42.; v2[2]=11.; cout<<v1*v2<<endl; //189 vec<double,2> v3; cout<<v1*v3<<endl; //deduced conflicting values for non-type parameter DIM ( 3u and 2u ) 16

Nontype templates (summary) template parameter can be value instead of type works for template classes and functions argument for nontype parameter must not be floating-poing numbers, classes, string literals each instantiation defines a new type 17

Compiling and linking Instantiations of template functions require knowledge of the implementation implementation in header file or #include mytemplateclass.cpp alternatives: explicit instantiation; export 18

more on templates details on templates + inheritance template argument deduction traits, policy classes meta programming recursively defined templates variadic templates (C++11) much more 19