Overview  Miscellaneous Utility Functions  Return Type Deduction  Generic Lambdas  Generalised Lambda Captures  C++14 Literals  constexpr Functions.

Slides:



Advertisements
Similar presentations
Lecture Computer Science I - Martin Hardwick The Programming Process rUse an editor to create a program file (source file). l contains the text of.
Advertisements

Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2003 Pearson Education, Inc. Slide 1.
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Chapter 1 C++ Basics. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 1-2 Learning Objectives Introduction to C++ Origins, Object-Oriented.
Yaser Zhian Dead Mage IGDI, Workshop 10, May 30 th -31 st, 2013.
Brown Bag #3 Return of the C++. Topics  Common C++ “Gotchas”  Polymorphism  Best Practices  Useful Titbits.
Brown Bag #2 Advanced C++. Topics  Templates  Standard Template Library (STL)  Pointers and Smart Pointers  Exceptions  Lambda Expressions  Tips.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Or: The Ampersand Recovery && Reinvestment Act of 2010 Stephan T. Lavavej Visual C++ Libraries Developer 1Version April 28, 2009.
The C ++ Language BY Shery khan. The C++ Language Bjarne Stroupstrup, the language’s creator C++ was designed to provide Simula’s facilities for program.
What's new in Microsoft Visual C Preview
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
C++ Basics Variables, Identifiers, Assignments, Input/Output.
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Announcements Quiz 1 Next Week. int : Integer Range of Typically -32,768 to 32,767 (machine and compiler dependent) float : Real Number (i.e., integer.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
 2006 Pearson Education, Inc. All rights reserved Arrays.
Computer Science II Exam I Review Monday, February 6, 2006.
C++ for Engineers and Scientists Third Edition
CSE 332: C++ Algorithms II From Last Time: Search with Generic Iterators Third generalization: separate iterator type parameter We arrive at the find algorithm.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Sorting and Vectors Mechanism for representing lists JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
CS 192 Lecture 3 Winter 2003 December 5, 2003 Dr. Shafay Shamail.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students Data representation and Data Types Variables.
COMPUTER PROGRAMMING. Data Types “Hello world” program Does it do a useful work? Writing several lines of code. Compiling the program. Executing the program.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Data Structures Using C++ 2E
Containers Overview and Class Vector
 2006 Pearson Education, Inc. All rights reserved Arrays.
1 Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation.
Introduction to C++ // Program description #include directives int main() { constant declarations variable declarations executable statements return.
1 C++ Syntax and Semantics, and the Program Development Process.
Basic Concepts of OOP in C++ Darvay Zsolt. C++ 2 Outline  The namespace and its members  The using declaration and directive  The address operator.
Array in C++ / review. An array contains multiple objects of identical types stored sequentially in memory. The individual objects in an array, referred.
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
CS212: Object Oriented Analysis and Design Lecture 2: Introduction to C++
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
COMPUTER PROGRAMMING. variable What is variable? a portion of memory to store a determined value. Each variable needs an identifier that distinguishes.
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
Variables and Data Types.  Variable: Portion of memory for storing a determined value.  Could be numerical, could be character or sequence of characters.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
C++ / G4MICE Course Session 2 Basic C++ types. Control and Looping Functions in C Function/method signatures and scope.
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
C++ Basics Programming. COMP104 Lecture 5 / Slide 2 Introduction to C++ l C is a programming language developed in the 1970s with the UNIX operating system.
1 CSC 1111 Introduction to Computing using C++ C++ Basics (Part 1)
Basic Types, Variables, Literals, Constants. What is in a Word? A byte is the basic addressable unit of memory in RAM Typically it is 8 bits (octet)
1 Chapter 1 C++ Templates Readings: Sections 1.6 and 1.7.
Generic Programming and Library Design Brian Bartman
Current Assignments Project 3 has been posted, due next Tuesday. Write a contact manager. Homework 6 will be posted this afternoon and will be due Friday.
C++ Lesson 1.
Variables, Identifiers, Assignments, Input/Output
Basics (Variables, Assignments, I/O)
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Instructor: Ioannis A. Vetsikas
Reserved Words.
C++ Functions, Classes, and Templates
Basics (Variables, Assignments, I/O)
Pointers, Dynamic Data, and Reference Types
Introduction to Programming
Variables, Identifiers, Assignments, Input/Output
Prof. Bhushan Trivedi Director GLS Institute of Computer Technology
Namespaces How Shall I Name Thee?.
2. Second Step for Learning C++ Programming • Data Type • Char • Float
Presentation transcript:

Overview  Miscellaneous Utility Functions  Return Type Deduction  Generic Lambdas  Generalised Lambda Captures  C++14 Literals  constexpr Functions  Variable Templates  Shared Mutexes and Locking  Improved Operators  Tuple Addressing via Type  Type Deduction and decltype(auto)

 std::make_unique  std::cbegin, std::cend, …  std::exchange  Robuust Sequence Operations  quoted Stream Manipulator

std::make_unique using namespace std; auto answer = make_unique (42); auto zero = make_unique (); auto array = make_unique (10); auto v = make_unique >(5,-1); struct Person { Person(string, string, int) {}; } auto me = make_unique ("Peter", "Van Weert", 1983); std::unique_ptr

1.make_unique (…) versus unique_ptr ( new LongTypeName(…) ); std::make_unique

1.make_unique (…) versus unique_ptr ( new LongTypeName[…] ); 2.f(unique_ptr (new X(…)), unique_ptr (new Y(…)), g(…)); versus f(make_unique (…), make_unique (…), g(…)); std::make_unique

Miscellaneous Utility Functions std::cbegin + std::cend ▫E.g. cbegin(myVector) i/o myVector.cbegin() ▫Works on C-style arrays ▫Convenient for templatised code ▫Also std::rbegin/rend, std::crbegin/crend std::exchange auto oldVal = std::exchange(x, newVal);

Miscellaneous Utility Functions Robuust Sequence Operations ▫ equal(v1.begin(),v1.end(), v2.begin())  equal(v1.begin(),v1.end(),v2.begin(),v2.end()) ▫Analogous for mismatch and is_permutation quoted Stream Manipulator ▫ cout << std::quoted("Hello World!"); > "Hello World!" ▫ cin << std::quoted(myString, '\''); < 'Hello Computer!!' assert(myString == "Hello Computer!!");

Other Miscellaneous Utilities Null forward iterators Discouraged use of rand() [[deprecated]] attribute …

 Lambda Expressions as Anonymous Functions

Lambda Expressions (C++11) std::vector v{ 7, 9, 7, 2, 0, 4 }; std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; } );

Function Objects (C++98) std::vector v{ 7, 9, 7, 2, 0, 4 }; struct Lambda { bool operator()(int a, int b) const { return a > b; } }; std::sort(v.begin(), v.end(), Lambda());

Lambda Expressions (C++11)

 Lambda Return Type Deduction (C++11)  Lambda Return Type Deduction (C++14)  Normal Function Return Type Deduction (C++14)

Lambda Return Type Deduction (C++11) using namespace std; vector v{ 7, 9, 7, 2, 0, 4 }; auto newEnd = remove_if(begin(v),end(v), [](int a) { return a % 2 == 1; } ); v.erase(newEnd, end(v)); std::for_each(cbegin(v), cend(v), [](int a) { cout << a << endl; } );

Lambda Return Type Deduction (C++11) using namespace std; vector v{ 7, 9, 7, 2, 0, 4 }; auto newEnd = remove_if(begin(v), end(v), [](int a) { if (a % 2 == 0) return false; cout << "Removed " << a << endl; return true; }); v.erase(newEnd, end(v));

Lambda Return Type Deduction (C++11)

Lambda Return Type Deduction (C++14) using namespace std; vector v{ 7, 9, 7, 2, 0, 4 }; auto newEnd = remove_if(begin(v), end(v), [](int a) { if (a % 2 == 0) return false; cout << "Removed " << a << endl; return true; }); v.erase(newEnd, end(v));

Lambda Return Type Deduction (C++14) using namespace std; string k3[] {"Karen","Kristel","Kathleen"}; transform(cbegin(k3), cend(k3), begin(k3), [](const string& s) { if (s.empty()) return " "; else return s.substr(0, 1); } );

Lambda Return Type Deduction (C++14)

Function Return Type Deduction (C++14) std::vector ::const_iterator

Function Return Type Deduction (C++14) auto find(const std::vector & v); /*...*/ auto find(const std::vector & v) { for (auto i = cbegin(v); i != cend(v); ++i) { if (*i == "Waldo") return i; } return cend(v); }

Function Return Type Deduction (C++14) auto fib(unsigned i) { if (i < 2) return 1ull; else return fib(i - 1) + fib(i - 2); } unsigned long long

Function Return Type Deduction (C++14) auto fib(unsigned i) { if (i >= 2) return fib(i - 1) + fib(i - 2); else return 1ull; }

Function Return Type Deduction (C++14) auto fib(unsigned i) { if (i >= 2) return fib(i - 1) + fib(i - 2); else return 1ull; }

Return Type Deduction C++11 ▫Lambda return type deduction (implicit ‘ -> auto ’) ▫Single return statement or void C++14 ▫Multiple statements ▫Multiple return statements of same type ▫Normal function return type deduction ( auto ) ▫Recursion once return type is deduced ▫Functions with auto return type cannot be virtual

Generic Lambdas

static auto plus = [](auto x, auto y) { return x + y; }; int (*fptr1)(int, int) = plus; double (*fptr2)(int, double) = plus; function f(plus); std::cout << plus(123,456) << std::endl;

Generic Lambdas static auto plus = [](auto&& x,auto&& y) { return x + y; }; struct Plus { template auto operator(T1&& x, T2&& y) const { return x + y; }; /* Function pointer conversion... */ };

 Lambda Captures (C++11)  Generalised Lambda Captures (C++14)

Lambda Captures (C++11) using namespace std; vector v{ 7, 9, 7, 2, 0, 4 }; float avg = Average(v); double std = sqrt(accumulate( cbegin(v), cend(v), 0., [](double acc, float x) { return acc + (x-avg) * (x-avg); } ));

Lambda Captures (C++11) using namespace std; vector v{ 7, 9, 7, 2, 0, 4 }; float avg = Average(v); double std = sqrt(accumulate( cbegin(v), cend(v), 0., [](double acc, float x) { return acc + (x-avg) * (x-avg); } ));

Lambda Captures (C++11) using namespace std; vector v{ 7, 9, 7, 2, 0, 4 }; float avg = Average(v); double std =...

Lambda Captures (C++11)

Generalised Lambda Captures (C++14)

Lambda Captures (C++11)

const unsigned num = 100; std::vector v(num); unsigned counter = 0; std::generate_n(v.begin(), num, [counter]() { return ++counter; } );

Lambda Captures (C++11) const unsigned num = 100; std::vector v(num); unsigned counter = 0; std::generate_n(v.begin(), num, [counter]() mutable { return ++counter; } );

Lambda Captures (C++11) const unsigned num = 100; std::vector v(num); const unsigned counter = 0; std::generate_n(v.begin(), num, [counter]() mutable { return ++counter; } );

Generalised Lambda Captures (C++14) const unsigned num = 100; std::vector v(num); const unsigned counter = 0; std::generate_n(v.begin(), num, [counter=counter]() mutable { return ++counter; } );

Generalised Lambda Captures (C++14) const unsigned num = 100; std::vector v(num); std::generate_n(v.begin(), num, [counter = 0u]() mutable { return ++counter; } );

Generalised Lambda Captures (C++14) const unsigned num = 100; std::vector v(num); std::generate_n(v.begin(), num, [/*auto */counter = 0u]() mutable { return ++counter; } );

C++14 [x=f(666)]Initialise auto-typed x with an expression [x=x]Initialise lambda-local x as a copy of x from surrounding scope [x, &y, z=42] Capture x by value, y by reference, and initialise z to 42 C++11 [x]Capture x by value [&x]Capture x by reference [=]Capture all by value [&]Capture all by reference [=,&x]Capture x by reference, everything else by value [&,x]Capture x by value, everything else by reference [this]Capture this pointer: can transparently access members of surrounding object

Lambda Captures (C++11) using Filter = std::function ; virtual Filter GetFilter(/*...*/) override { using namespace std; unordered_set huge; /* Gather strings in huge... */ return [=](const string& s ) { return huge.count( s ) > 0; } }

Lambda Captures (C++11)

Generalised Lambda Captures (C++14)

 Binary Literals  Digit Separators  User-defined Literals for Standard Library Types

Binary Literals std::cout << ; 101

Binary Literals

Digit Separators Motivating examples ▫Pronounce ▫Are and equal? ▫Is larger than ?

Digit Separators Motivating examples ▫Pronounce 7'237'498'123 ▫Are 237'498'123 and 237'499'123 equal? ▫Is 237'499'123 larger than 20'249'472 ? C++14 integer literals ▫ == 1'048'576 == 10'48'576 == 0x10'0000 == 0'004'000'000 == 0b ' ' C++14 floating point literals ▫ e-19 == 1.602'176'565e-19

User-defined Literals for STL Types using namespace std::literals; auto hello = "Hello World"s; auto minute = 60s; auto hour = 60m; auto day = 24h; auto second = 1'000ms; auto milliSec = 1'000us; auto microSec = 1'000ns; std::string std::chrono::minutes std::chrono::microseconds

User-defined Literals for STL Types using namespace std::literals; auto hello = "Hello World"s; auto minute = 60s; auto hour = 60m; auto day = 24h; auto second = 1'000ms; auto milliSec = 1'000us; auto microSec = 1'000ns; std::chrono::duration >

User-defined Literals for STL Types namespace std { inline namespace literals { inline namespace string_literals { basic_string operator""s(const char *str, size_t len); basic_string operator""s(const wchar_t *str, size_t l); /*...*/ }}}

User-defined Literals for STL Types

using namespace std::literals::complex_literals; auto a = 10i; auto b = 1.23e-4i; auto c = 42if; auto d =.5il; auto e = i; auto f = 1.f + 2i; auto g = 1.l + 2il; std::complex

User-defined Literals for STL Types using namespace std::literals::complex_literals; auto a = 10i; auto b = 1.23e-4i; auto c = 42if; auto d =.5il; auto e = i; auto f = 1.f + 2i; auto g = 1.l + 2il; std::complex

User-defined Literals for STL Types using namespace std::literals::complex_literals; auto a = 10i; auto b = 1.23e-4i; auto c = 42if; auto d =.5il; auto e = i; auto f = 1.f + 2i; auto g = 1.l + 2il; std::complex

constexpr Functions / Variables (C++11) Function/variable evaluateable at compile time Uses: ▫As size of fixed-size arrays ▫As template argument ▫In static_assert ▫… constexpr size_t Fib(size_t x) { return x < 2? 1 : Fib(x-2) + Fib(x-1); } static_assert(Fib(6) == 13, "Must be Friday"); int bigArray[Fib(21)];

constexpr Functions (C++11) Non-virtual Return type and parameters must be literal types Use only literal values, and constexpr variables and functions Function body: single return statement ▫Also allowed: null statements, static_assert -declarations, typedef declarations and alias-declarations that do not define classes or enumerations, using -declarations, and using -directives A constexpr function is implicitly const

constexpr Functions (C++14) Non-virtual Return type and parameters must be literal types Use only literal values, and constexpr variables and functions Function body: anything ▫Except  asm -definition, goto statement, try -block, and definition of a variable of non-literal type, or of static or thread storage duration, or for which no initialization is performed A constexpr function does not need to be const ▫When used in a constexpr expression, only modify class members of objects whose lifetime began within the constant expression evaluation

Variable Templates template constexpr T pi = T( ); template constexpr T GetAreaOfCircle(T radius) { return radius * radius * pi ; }

Variable Templates template constexpr Matrix identity = Matrix ::CreateIdentity(); auto test2x2 = identity ; auto test3x3 = identity, 3>;

 Multiple-Readers / Single-Writer Locking  class shared_timed_mutex  template class shared_lock

typename std::queue ::const_reference

class shared_timed_mutex Header: Mutex (≈ std:: mutex ) ▫Uncopyable + void lock() + void unlock() ▫Works with lock_guard, unique_lock, and lock() Timed mutex(≈ std:: timed_mutex ) ▫ bool try_lock(), bool try_lock_for(const chrono::duration&), bool try_lock_until(const chrono::time_point&) ▫Works with unique_lock and try_lock() Shared mutex + shared timed mutex ▫All above functions with ‘ lock_shared ’ i/o ‘ lock ’ ▫Works with shared_lock

template class shared_lock Header: RAII type for (timed) shared mutex Analogous to std::unique_lock ▫Same set of constructors ▫Same functions: lock(), try_lock() + variants, etc. ▫Always calls lock_shared() / try_lock_shared() ▫Works e.g. with std::condition_variable  Use case: release shared lock until data is ready to read

 Improved Operators  Heterogeneous Lookup in Associative Containers

Improved Operators using namespace std; vector v{ 7, 9, 7, 2, 0, 4 }; sort(v.begin(), v.end(), greater ());// C++98 sort(v.begin(), v.end(), greater<>()); // C++14 vector ss{ "Apple","Bar","Foo" }; string s("Charlie"); // C++98: homogeneous operator: temp string objects auto lb1 = lower_bound(ss.begin(), ss.end(), s); // C++14: heterogeneous operator: no temp objects auto lb2 = lower_bound(ss.begin(), ss.end(), s, less<>());

Heterogeneous Comparison in Associative Containers Example: find, lower_bound, equal_range etc. in set of string using const char* ▫Not possible with set (even in C++14) ▫Possible with set > Heterogeneous comparison allowed for operators that define a type is_transparent template struct Compare { typedef bool is_transparent; bool operator( T && a, U && b ) const { /*...*/ } };

using std::string; std::tuple me {"Peter", "Van Weert", 1983}; int i = std::get (me);// C++11 int j = std::get (me);// C++14 Tuple Addressing via Type

using std::string; std::tuple me {"Peter", "EJ", "Van Weert", 1983}; int i = std::get (me); // C++11 int j = std::get (me); // C++14 auto s = std::get (me); Tuple Addressing via Type

 auto and decltype (C++11)  delctype(auto) (C++14)  Type Deduction Revisited

Type Deduction Rules (C++11) Three sets of rules 1. Template type deduction 2. auto 3. decltype(x) Difference (1) and (2) ▫Deduced type for x in “ auto x = { 1, 2, 3 }; ”, is std::initializer_list ▫Template type deduction fails on expressions like “ {1, 2, 3} ”

Type Deduction Rules (C++11) Three sets of rules 1. Template type deduction 2. auto 3. decltype(x) Difference (1) and (2): initializer lists Difference (3) and others

Type Deduction Rules (C++11) int i = 1; const int constI = 1; int& refI = i; auto autoValI = 1; // int auto autoI = i; // int auto autoConstI = constI; // int auto autoRefI = refI; // int auto autoMoveI = std::move(i); // int

Type Deduction Rules (C++11) int i = 1; const int constI = 1; int& refI = i; auto&& univValI = 1; // int&& auto&& univI = i; // int& auto&& univConstI = constI; // const int& auto&& univRefI = refI; // int& auto&& univMoveI = std::move(i); // int&&

Type Deduction Rules (C++11) int i = 1; const int constI = 1; int& refI = i; decltype(1) dtValI = 1; // int decltype(i) dtI = i; // int decltype(constI) dtConstI = constI; // const int decltype(refI) dtRefI = refI;// int& decltype(std::move(i)) dtMoveI = std::move(i);// int&&

Type Deduction Rules (C++11) Three sets of rules 1. Template type deduction 2. auto 3. decltype(x) Difference (1) and (2): initializer lists Difference (3) and others ▫(1) and (2) remove reference (lvalue and rvalue), const, and volatile qualifiers; (3) doesn’t ▫ auto&& retains qualifiers, but adds lvalue reference to non-reference type

Type Deduction Rules (C++11) int i = 1; const int constI = 1; int& refI = i; decltype(1) dtValI = 1; // int decltype(i) dtI = i; // int decltype(constI) dtConstI = constI; // const int decltype(refI) dtRefI = refI;// int& decltype(std::move(i)) dtMoveI = std::move(i);// int&&

Type Deduction Rules (C++14) int i = 1; const int constI = 1; int& refI = i; decltype(auto) dtaValI = 1; // int decltype(auto) dtaI = i; // int decltype(auto) dtaConstI = constI; // const int decltype(auto) dtaRefI = refI; // int& decltype(auto) dtaMoveI = std::move(i); // int&&

Type Deduction Revisited Lambda return type deduction (C++11) ▫Implicit “-> auto ” ▫Use trailing return type to override (C++14)  “-> auto& ”, “-> auto&& ”, “ -> decltype(auto) ”, … Function return type deduction (C++14) ▫Default: explicit auto ▫Also allowed: auto&, auto&&, decltype(auto), … Arguments of generic lambdas (C++14) ▫Template argument type deduction ▫Also allowed: auto&, auto&&, decltype(auto), …