Modern and Lucid C++ Advanced for Professional Programmers. Part 7 Compile-Time Computation. Department I - C Plus Plus

Size: px
Start display at page:

Download "Modern and Lucid C++ Advanced for Professional Programmers. Part 7 Compile-Time Computation. Department I - C Plus Plus"

Transcription

1 Department I - C Plus Plus Modern and Lucid C++ Advanced for Professional Programmers Part 7 Compile-Time Computation Thomas Corbat / Prof. Peter Sommerlad Rapperswil, HS2017

2 Topics 2 SFINAE Compile-Time Computation (Legacy) User-Defined Literals C++14 Features (If there is time)

3 SFINAE

4 Overload Selection 4 What do you expect is the return value of the program on the right? None, the program does not compile! Name increment is looked up increment(unsinged) increment Template Template arguments are deduced unsigned increment(unsigned i) { return i++; template<typename T> T increment(t value) { return value.increment(); int main() { return increment(42); increment(unsigned) increment<int>(int) Best overload is selected error: request for member 'increment' in 'value', which is of non-class type 'int' increment(int)

5 Substitution Failure Is Not An Error 5 During overload resolution the template parameters in a template declaration are substituted with the deduced types This may result in template instances that cannot be compiled Or otherwise suboptimal selection If the substitution of template parameter fails that overload candidate is discarded Substitution failure might happen in Function return type Function parameter Substitution Template parameter declaration And expressions in the above Errors in the instance body are still errors Substitution template<typename T> T increment(t value) { return value.increment(); int increment(int value) { return value.increment(); //T = int Substitution

6 Possible Solution (Not Recommended) 6 We can break the return type template<typename T> auto increment(t value) -> decltype(value.increment()) { return value.increment(); If we tell the compiler to use the type of value.increment() as return type for increment<int> That type cannot be determined during substitution error: no matching function for call to 'increment(int)' increment(42); ^ note: candidate: template<class T> decltype (value.increment()) increment(t) auto increment(t value) -> decltype(value.increment()) { ^~~~~~~~~ note: template argument deduction/substitution failed: In substitution of 'template<class T> decltype (value.increment()) increment(t) [with T = int]': error: request for member 'increment' in 'value', which is of non-class type 'int' auto increment(t value) -> decltype(value.increment()) {

7 Overload Selection with SFINAE 7 7 Since there is a problem during substitution that overload is discarded Name increment is looked up increment(unsinged) Template arguments are deduced increment(unsigned) increment Template increment<int>(int) unsigned increment(unsigned i) { return i++; template<typename T> auto increment(t value) -> decltype(value.increment()) { return value.increment(); int main() { return increment(42); Now the result is 42 Best overload is selected increment(unsigned) This approach, using decltype(...) as trailing return type, is infeasible in general Function might have return type void It is not elegant for complex bodies

8 std::is_class Let's examine our example again 8 <type_traits> We want the increment template to be selected only for class type arguments There exists a template std::is_class<t> contains static constexpr bool value; value is true if T is a class, false otherwise template<typename T> T increment(t value) { return value.increment(); int main() { return increment(42); In C++17 we will have std::is_class_v<t> A variable template of type bool (direct ::value) Can we apply this to the increment template directly? No, either value (true or false) is still valid We need something to create an error in the type of the function #include <type_traits> struct S {; int main() { std::is_class<s>::value; //true std::is_class<int>::value; //false

9 std::enable_if / std::enable_if_t template<bool expr, typename T = void> struct enable_if; 9 <type_traits> The std::enable_if_t template takes an expression and a type If the expression evaluates to true std::enable_if_t represents the given type Otherwise it does NOT represent a type int main() { std::enable_if_t<true, int> i; //int std::enable_if_t<false, int> error; //no type Inside std::enable_if template<bool expr, typename T = void> struct enable_if {; template<typename T> struct enable_if<true, T> { using type = T; ; template<bool expr, typename T = void> using enable_if_t = typename enable_if<expr, T>::type;

10 std::enable_if Applied 10 template<typename T, > T increment( T value) { return value.increment(); Spots to apply enable_if (SFINAE) Possibilities template<typename T> std::enable_if_t<std::is_class<t>::value, T> increment(t value) { return value.increment(); template<typename T> T increment(std::enable_if_t<std::is_class<t>::value, T> value) { return value.increment(); enable_if as parameter impairs type deduction template<typename T, typename = std::enable_if_t<std::is_class<t>::value, void>> T increment(t value) { return value.increment(); would be void per default

11 Compile-Time Computation

12 C++14 Compile-Time Computation 12 ROMable data (guaranteed!) Plain C++ Simpler than in C++03 Not yet everything possible provided Standard library not made up for everything desirable Compile times can increase horrendously Example that is supposed to take 24h to be compiled

13 C++03 Basic Features 13 (static) const variables in namespace scope of built-in types initialized with constant expression are usually put into ROMable memory, if at all. Allowed in constant expression context No complicated computations (except with macros) No guarantee to be done at compile-time in all cases size_t const SZ = 6 * 7; double x[sz]; Constant expression context Compile-time evaluation

14 C++03 Compile-Time Computation 14 template <size_t n> struct fact { static size_t const value{(n > 1)? n * fact<n-1>::value : 1; ; template <> struct fact<0> { // recursion base case: template specialization static size_t const value = 1; ; int a[fact<5>::value]; // check compile-time constant void testfactorialcompiletime() { ASSERT_EQUAL(sizeof(a), sizeof(int) * 2 * 3 * 4 * 5); "Integer" only (almost) through non-type template parameters Would need out-of-class static member variable definition for ODR-use at run-time or C++11 constexpr

15 C++03 Compile-Time Computation 15 Templates allow Turing-complete computation But it looks ugly and can be hard to understand Compiler error-messages can be lengthy Compile-time long and recursion depth limited (depends on the compiler and its settings) Almost only single values can be computed Arrays/structs possible, but ugly Observation: static const member variables of class templates are variables that depend on template parameters

16 C++11 Feature: constexpr Variables and static_assert() 16 constexpr size_t SZ{7 * 3 * (1 + 1); constexpr double x[sz] {1, 2, 3, 4, 5, 6, 7, 8, ; Constexpr variable: Guaranteed compile-time evaluation Can be used in constant expression contexts static_assert checked at compile-time (static) Syntax: static_assert(cond, message); //in C++17 message will be optional static_assert(sizeof(x) == 42 * sizeof(double), "size of array x unexpected"); static_assert(x[3] + x[4] == 9, "expect x initialized at compile-time"); void testsizeofandinitofx() { ASSERT_EQUAL(42 * sizeof(double), sizeof(x)); double const *px = x; // take address to make sure it exists in memory ASSERT_EQUAL(1, *px); // access first element

17 C++11 Compile-Time Computation 17 constexpr unsigned long long fact(unsigned short n) { return n > 1? n * fact(n - 1) : 1; int a[fact(5)]; void testfactorialcompiletime() { ASSERT_EQUAL(sizeof(int) * 2 * 3 * 4 * 5, sizeof(a)); Only 1 statement and recursion allowed in constexpr functions Overflow is a compile-error No local variables, but any "literal" type Simpler syntax than C++03 templates but not much more expressive, except for doubles

18 C++11 Compile-Time Computation 18 constexpr double factd(unsigned short n) { return n > 1? n * factd(n - 1) : 1; constexpr auto fac5 = factd(5); static_assert(120 == fac5, "see if doubles compare equal"); void testfactdouble(){ int i = 3 + fact(2); ASSERT_EQUAL(120.0, factd(i)); Can compute with floating point values at compile-time, but only single statement (return statement) in constexpr function Constexpr function: If used in constexpr context, guaranteed compile-time evaluation, otherwise run-time evaluation is possible Thus you can call constexpr functions from contexts where its arguments are not compile-time constant

19 C++11 Allows Generic constexpr 19 template <typename T> constexpr T abs(t x){ return x < 0? - x : x; static_assert(5 == abs(-5), "abs is correct for negative int"); static_assert(5 == abs(5), "abs is correct for int"); static_assert(5.0 == abs(-5.0), "abs is correct for negative double"); static_assert(5.0l == abs(-5.0l), "abs is correct for negative long double"); Return type must be specified, but it can be duduced It is better to use the abs (C++) function than a macro, as it is type-safe Also works at compile-time, which can be prooven by the static_asserts Single return statement restriction in C++11

20 Reminder: Functions, Temlpates and Patterns 20 Function overload resolution Pattern matching through call arguments Function template Template argument deduction from call arguments Class template: Implementation selection through (partial) specialization Pattern matching through template arguments

21 C++11 Literal Types 21 Trivial Types Built-in types, arrays of trivial types, structs of trivial types Without initializers, special member functions defined or virtual members with only trivial bases Literal Types: like Trivial structs/classes + constexpr constructor/initialization and trivial destructor (not user defined!) Literal Types can be used in constexpr functions, but only constexpr member functions can be called on values of literal type POD + constexpr constructor + trivial destructor + constexpr member functions

22 C++11 Standard Mistake: Literal Types 22 C++11 defined constexpr member functions to be implicitly const That turned out to be a problem with C++14! Incompatible change with C++14 (a quick fix) If a constexpr member function (in a literal type) is const, you need to specify it. Quiz: Does it make sense to have non-const constexpr member functions?

23 User-Defined Literals

24 Motivation for UDL 24 Type for velocity struct speed { /*constexpr?*/ /*explicit?*/ speed(long double kmh) : kmh { kmh { long double const kmh; ; Can be used in Example speed s {5.0; speed s = 5.0; auto s = 5.0; auto s = speed{5.0 Valid Yes Non-explicit Not a speed object Yes

25 Drawback of speed 25 Repetitive occurrence of explicit conversion speed{x What if we would like to have different units? e.g. mph? constexpr double MPH_TO_KMH { ; auto s_mph = speed{5.0 * MPH_TO_KMH; Alternative: User-defined literals auto s_kmh = 5.0_kmh; auto s_mph = 5.0_mph;

26 User-Defined Literals 26 Problem: Constants lack a dimension Can result in hard to detect bugs Overloading operator"" _UDLSuffix() UDLSuffix could lexically be any identifier, but must start with underscore _ (other suffixes are reserved for the standard) Allows to add dimension, conversion, etc. If possible define UDL operator functions as constexpr Add the suffix to integer, float and string literals Suffix belongs to literal (no whitespace between) 5.0_kmh; //correct 5.0 _mph; //wrong Rule: put overloaded UDL operators that belong together in a separate namespace Only a using namespace can import them

27 User-Defined Literals for speed 27 namespace velocity { constexpr double MPH_TO_KMH { ; struct speed { constexpr explicit speed(long double kmh) : kmh { kmh { long double const kmh; ; constexpr speed operator"" _kmh(long double kmh) { return speed{kmh; constexpr speed operator"" _mph(long double mph) { return speed{mph * MPH_TO_KMH;

28 User-Defined Literals for speed 28 using namespace velocity; void test_mph_operator() { ASSERT_EQUAL_DELTA(8.05_kmh, 5.0_mph, 0.01_kmh); Shorter and more expressive literals Beware: The ASSERT_EQUAL_DELTA macro above needs a bit more functionality in speed: operator long double() const;

29 User-Defined Literal Signatures (1/4) 29 For literal numbers the following signatures are useful Integral constants TYPE operator "" _suffix(unsigned long long) Example constexpr speed operator"" _kmh(unsigned long long kmh) { return speed{static_cast<long double>(kmh); auto s_kmh = 5_kmh; Floating point constants TYPE operator "" _suffix(long double)

30 User-Defined Literal Signatures (2/4) 30 For string literals the following signature is useful TYPE operator "" _suffix(char const *, std::size_t len) namespace mystring { std::string operator"" _s(char const *s, std::size_t len) { return std::string { s, len ; Note: Implementation above cannot be constexpr. Why? Example: using namespace mystring; auto s = "hello"_s; s += " world\n"; std::cout << s;

31 User-Defined Literal Signatures (3/4) 31 RAW UDL Operator TYPE operator "" _suffix(char const *) namespace mystring { std::string operator"" _s(char const *s) { return std::string { s ; Note: Works only for integral and floating literals, not for string literals! Example: using namespace mystring; auto rs = 42_s; rs += " raw\n"; std::cout << rs;

32 Raw UDL Operator Applied 32 Ternary suffix Base 3 Examples Ternary Decimal namespace ternary { unsigned long long operator"" _3(char const *s) { size_t convertedupto{; auto res = std::stoull(s, &convertedupto, 3u); if (convertedupto!= strlen(s)) throw std::logic_error { "invalid ternary" ; return res; using namespace ternary; int four = 11_3; std::cout << "four is " << four << '\n'; try { four = 14_3; // throws catch (std::exception const &e) { std::cout << e.what() << '\n'; Problem: exception at run-time

33 User-Defined Literal Signatures (4/4) 33 Template UDL Operator template<char...> TYPE operator "" _suffix() Empty parameter list Variadic template parameter Characters of the literal are template arguments 120_ternary; // => operator "" _ternary() // with template arguments '1', '2' and '0' Unfortunately, the template UDL operator does not work with string literals

34 Raw UDL Extreme: Ternary Number at Compile-Time (1/3) 34 Run-time errors for number conversion is bad There exists a variadic template version of UDL operators Interpretation of the characters (at compile-time) often requires a variadic class/variable template with specializations template<char...digits> constexpr unsigned long long operator"" _ternary() { return _impl::ternary_value<digits...>; We will also need a helper function to get the value of the digit: 3 n constexpr unsigned long long three_to(std::size_t power) { return power? 3ull * three_to(power - 1) : 1ull;

35 Raw UDL Extreme: Ternary Number at Compile-Time (2/3) 35 template<char...digits> extern unsigned long long ternary_value; template<char...digits> constexpr unsigned long long ternary_value<'0', Digits...> { ternary_value<digits...> ; template<char...digits> constexpr unsigned long long ternary_value<'1', Digits...> { 1 * three_to(sizeof...(digits)) + ternary_value<digits...> ; template<char...digits> constexpr unsigned long long ternary_value<'2', Digits...> { 2 * three_to(sizeof...(digits)) + ternary_value<digits...> ; template<> constexpr unsigned long long ternary_value<>{0;

36 Raw UDL Extreme: Ternary Number at Compile-Time (3/3) Slide not found! No slide "Raw UDL Extreme: Ternary Number at Compile-Time (3/3)" needed There used to be three with C++11 before variable templates now it is only two The class templates containing the value looked as follows (specialization for '0') template<char...digits> //Case for '0' struct parse_ternary<'0', Digits...> { static unsigned long long const value { parse_ternary<digits...>::value ; ;

37 Ternary Number Compile-Time Steps 37 Example: 120_ternary 120_ternary -> resolves to ternary_value<'1', '2', '0'> Partial specialization: ternary_value<'1', Digits...> Value: 1 * ternary_value<'2', '0'> Partial specialization: ternary_value<'2', Digits...> Value: 2 * ternary_value<'0'> Partial specialization: ternary_value<'0', Digits...> Value: ternary_value<> Partial specialization: parse_ternary<> Value: 0 Value: 0 Value: 6 from 2 * Value: 15 from 1 *

38 Ternary Number Compile-Time Restrictions 38 Can we avoid the duplication of the specialization for '0', '1' and '2'? constexpr bool is_ternary_digit(char c) { return c == '0' c == '1' c == '2'; constexpr unsigned value_of(char c) { return c - '0'; template<char D, char...digits> constexpr std::enable_if_t<is_ternary_digit(d), unsigned long long> ternary_value<d, Digits...> { value_of(d) * three_to(sizeof...(digits)) + ternary_value<digits...> ;

39 Ternary Number: static_assert 39 The declaration of value is barely readable; let s try static_assert static_assert(cond, msg); It is a declaration itself and thus cannot be used with variable templates template<char D> constexpr unsigned value_of() { static_assert(is_ternary_digit(d), "Digits of ternary must be 0, 1 or 2"); return D - '0'; template<char D, char...digits> constexpr unsigned long long ternary_value<d, Digits...> { value_of<d>() * three_to(sizeof...(digits)) + ternary_value<digits...> ; Nice error message during compilation static_assert prevents SFINAE

40 Ternary Number: Outlook to C++20 (maybe) 40 Upcomming alternative: Concepts concept keyword Concept name used instead of typename Nice compiler messages template<char D> concept bool TernaryDigit = is_ternary_digit(d); template<ternarydigit D, TernaryDigit...Digits> constexpr unsigned long long ternary_value<d, Digits...> {...;..\main.cpp: In function 'int main(int, char**)':..\main.cpp:40:27: error: cannot call function 'long long unsigned int ternary::operator""_t() [with char...digits = {'1', '4']' std::cout << "14_t: " << 14_t << std::endl; ^~~~..\main.cpp:30:20: note: constraints not satisfied unsigned long long operator "" _t() { ^~~~~~~~..\main.cpp:30:20: note: in the expansion of 'TernaryDigit<Digits>...'..\main.cpp:30:20: note: 'TernaryDigit<'4'>' was not satisfied

41 Standard Literal Suffixes 41 Standard suffixes don t have a leading underscore Suffix for std::string: s Suffix for std::complex (imaginary): i, il, if Suffixes for std::chrono::duration: ns, us, ms, s, min, h More might be defined in the future Is the following example a problem? using namespace std::string_literals; using namespace std::chrono_literals; auto one_s = 1s; auto one_point_zero_s = 1.0s; auto fourty_two_s = "42"s;

42 Summary UDL 42 User-defined Literals can help to get dimensions of constants right as a short-hand for type conversions to implement compile-time constants of literal types obfuscate program code if applied mercilessly If constexpr, user-defined literals are resolved at compile-time No runtime-overhead Don t specify suffixes for all your types now!

Using Enum Structs as Bitfields

Using Enum Structs as Bitfields New York C++ Developers Group July 12, 2016 Using Enum Structs as Bitfields Presentation by Jon Kalb Based on an article in Overload magazine by Anthony Williams 1 What do these have in common?! explicit

More information

Part X. Advanced C ++

Part X. Advanced C ++ Part X Advanced C ++ topics Philip Blakely (LSC) Advanced C++ 158 / 217 References The following are highly regarded books. They are fairly in-depth, and I haven t read them in their entirity. However,

More information

An Introduction to Template Metaprogramming

An Introduction to Template Metaprogramming An Introduction to Template Metaprogramming Barney Dellar Software Team Lead Toshiba Medical Visualisation Systems Caveat I decided to do this talk after getting thoroughly lost on the recent talk on SFINAE.

More information

Modern and Lucid C++ Advanced for Professional Programmers. Part 3 Move Semantics. Department I - C Plus Plus Advanced

Modern and Lucid C++ Advanced for Professional Programmers. Part 3 Move Semantics. Department I - C Plus Plus Advanced Department I - C Plus Plus Advanced Modern and Lucid C++ Advanced for Professional Programmers Part 3 Move Semantics Thomas Corbat / Prof. Peter Sommerlad Rapperswil, 09.03.2018 HS2018 Move Semantics 2

More information

P1267R0: Custom Constraint Diagnostics

P1267R0: Custom Constraint Diagnostics P1267R0: Custom Constraint Diagnostics ISO/IEC JTC1 SC22/WG21 - Programming Languages - C++ Authors: Hana Dusíková < hana.dusikova@avast.com > Bryce Adelstein Lelbach < brycelelbach@gmail.com > Audience:

More information

TDDD38 - Advanced programming in C++

TDDD38 - Advanced programming in C++ TDDD38 - Advanced programming in C++ Templates III Christoffer Holm Department of Computer and information science 1 Dependent Names 2 More on Templates 3 SFINAE 1 Dependent Names 2 More on Templates 3

More information

C++ Modern and Lucid C++ for Professional Programmers

C++ Modern and Lucid C++ for Professional Programmers Informatik C++ Modern and Lucid C++ for Professional Programmers Part 1 Self-study for Introduction to C++ Prof. Peter Sommerlad Director IFS Institute for Software Rapperswil, HS 2017 Thomas Corbat Additional

More information

Basic Types, Variables, Literals, Constants

Basic Types, Variables, Literals, Constants 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) But some machines had 7, or 9, or... A word is the basic

More information

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

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things. A Appendix Grammar There is no worse danger for a teacher than to teach words instead of things. Marc Block Introduction keywords lexical conventions programs expressions statements declarations declarators

More information

Assignment #1 Advanced Programming in C /2018. NPRG051 Advanced programming in C++ - Assignment #1

Assignment #1 Advanced Programming in C /2018. NPRG051 Advanced programming in C++ - Assignment #1 Assignment #1 Advanced Programming in C++ 2017/2018 1 Assignment #1 split deadline: Thu 12 Apr 23:59 2 using namespace splitter; std::istringstream iss("alpha:=10/50.1"); std::string x; int y; double z;

More information

CS

CS CS 1666 www.cs.pitt.edu/~nlf4/cs1666/ Programming in C++ First, some praise for C++ "It certainly has its good points. But by and large I think it s a bad language. It does a lot of things half well and

More information

Overview. 1. Expression Value Categories 2. Rvalue References 3. Templates 4. Miscellaneous Hilarity 2/43

Overview. 1. Expression Value Categories 2. Rvalue References 3. Templates 4. Miscellaneous Hilarity 2/43 Advanced C++ 1/43 Overview 1. Expression Value Categories 2. Rvalue References 3. Templates 4. Miscellaneous Hilarity 2/43 1. Expression Value Categories These are not the droids you re looking for ~Obi-wan

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

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below: QUIZ 1. Explain the meaning of the angle brackets in the declaration of v below: This is a template, used for generic programming! QUIZ 2. Why is the vector class called a container? 3. Explain how the

More information

Variables. Data Types.

Variables. Data Types. Variables. Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable. We had to write several lines of code, compile them, and then execute the resulting

More information

MODERN AND LUCID C++ ADVANCED

MODERN AND LUCID C++ ADVANCED Informatik MODERN AND LUCID C++ ADVANCED for Professional Programmers Prof. Peter Sommerlad Thomas Corbat Director of IFS Research Assistant Rapperswil, FS 2016 LIBRARY API/ABI DESIGN PIMPL IDIOM HOURGLASS

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

Other C++11/14 features

Other C++11/14 features Other C++11/14 features Auto, decltype Range for Constexpr Enum class Initializer list Default and delete functions Etc. Zoltán Porkoláb: C++11/14 1 Auto, decltype template void printall(const

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

Part III. Advanced C ++

Part III. Advanced C ++ Part III Advanced C ++ topics Philip Blakely (LSC) Advanced C++ 66 / 119 References The following are highly regarded books. They are fairly in-depth, and I haven t read them in their entirity. However,

More information

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab. University of Technology Laser & Optoelectronics Engineering Department C++ Lab. Second week Variables Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable.

More information

Modern and Lucid C++ Advanced for Professional Programmers. Part 1 C Plus Plus Recap. Department I - C Plus Plus

Modern and Lucid C++ Advanced for Professional Programmers. Part 1 C Plus Plus Recap. Department I - C Plus Plus Department I - C Plus Plus Modern and Lucid C++ Advanced for Professional Programmers Part 1 C Plus Plus Recap Thomas Corbat / Prof. Peter Sommerlad Rapperswil, 23.02.2018 HS2018 Values vs. References

More information

Structured bindings with polymorphic lambas

Structured bindings with polymorphic lambas 1 Introduction Structured bindings with polymorphic lambas Aaryaman Sagar (aary800@gmail.com) August 14, 2017 This paper proposes usage of structured bindings with polymorphic lambdas, adding them to another

More information

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University Fundamental Data Types CSE 130: Introduction to Programming in C Stony Brook University Program Organization in C The C System C consists of several parts: The C language The preprocessor The compiler

More information

Ch. 10: Name Control

Ch. 10: Name Control Ch. 10: Name Control Static elements from C The static keyword was overloaded in C before people knew what the term overload meant, and C++ has added yet another meaning. The underlying concept with all

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

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

Overload Resolution. Ansel Sermersheim & Barbara Geller Amsterdam C++ Group March 2019 Ansel Sermersheim & Barbara Geller Amsterdam C++ Group March 2019 1 Introduction Prologue Definition of Function Overloading Determining which Overload to call How Works Standard Conversion Sequences Examples

More information

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

Overload Resolution. Ansel Sermersheim & Barbara Geller ACCU / C++ June 2018 Ansel Sermersheim & Barbara Geller ACCU / C++ June 2018 1 Introduction Definition of Function Overloading Determining which Overload to call How Overload Resolution Works Standard Conversion Sequences

More information

New Tools for Class and Library Authors

New Tools for Class and Library Authors New Tools for Class and Library Authors By Scott Schurr for C++ Now! 2012 Topics o _Pragma o static_assert o explicit conversion operators o decltype o constexpr o variadic templates 2 _Pragma o Borrowed

More information

boost::enable_if Deep Down Boostimagical Fun Christian Bay and Kasper A Andersen Department of Computer Science University of Copenhagen

boost::enable_if Deep Down Boostimagical Fun Christian Bay and Kasper A Andersen Department of Computer Science University of Copenhagen Deep Down Boostimagical Fun boost::enable_if Christian Bay and Kasper A Andersen Department of Computer Science University of Copenhagen C. Bay and K. A. Andersen, June 2, 2006 p. 1/12 SFINAE revisited

More information

Modern and Lucid C++ Advanced for Professional Programmers. Part 12 Advanced Library Design. Department I - C Plus Plus Advanced

Modern and Lucid C++ Advanced for Professional Programmers. Part 12 Advanced Library Design. Department I - C Plus Plus Advanced Department I - C Plus Plus Advanced Modern and Lucid C++ Advanced for Professional Programmers Part 12 Advanced Library Design Thomas Corbat / Prof. Peter Sommerlad Rapperswil, 23.02.2017 HS2017 Topics

More information

Tokens, Expressions and Control Structures

Tokens, Expressions and Control Structures 3 Tokens, Expressions and Control Structures Tokens Keywords Identifiers Data types User-defined types Derived types Symbolic constants Declaration of variables Initialization Reference variables Type

More information

Programming, numerics and optimization

Programming, numerics and optimization Programming, numerics and optimization Lecture A-2: Programming basics II Łukasz Jankowski ljank@ippt.pan.pl Institute of Fundamental Technological Research Room 4.32, Phone +22.8261281 ext. 428 March

More information

Outline. 1 About the course

Outline. 1 About the course Outline EDAF50 C++ Programming 1. Introduction 1 About the course Sven Gestegård Robertz Computer Science, LTH 2018 2 Presentation of C++ History Introduction Data types and variables 1. Introduction 2/1

More information

Cpt S 122 Data Structures. Templates

Cpt S 122 Data Structures. Templates Cpt S 122 Data Structures Templates Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Introduction Function Template Function-template and function-template

More information

C++11 Introduction to the New Standard. Alejandro Cabrera February 1, 2012 Florida State University Department of Computer Science

C++11 Introduction to the New Standard. Alejandro Cabrera February 1, 2012 Florida State University Department of Computer Science C++11 Introduction to the New Standard Alejandro Cabrera February 1, 2012 Florida State University Department of Computer Science Overview A Brief History of C++ Features Improving: Overall Use Meta-programming

More information

Programming in C++ 4. The lexical basis of C++

Programming in C++ 4. The lexical basis of C++ Programming in C++ 4. The lexical basis of C++! Characters and tokens! Permissible characters! Comments & white spaces! Identifiers! Keywords! Constants! Operators! Summary 1 Characters and tokens A C++

More information

The C++ Programming Language, Core Working Group. Title: Unary Folds and Empty Parameter Packs (revision 1)

The C++ Programming Language, Core Working Group. Title: Unary Folds and Empty Parameter Packs (revision 1) 1 Document number: P0036 Date: 2015-09-10 Project: The C++ Programming Language, Core Working Group Title: Unary Folds and Empty Parameter Packs (revision 1) Revises: N4358 Reply-to: Thibaut Le Jehan lejehan.thibaut@gmail.com

More information

C++ Template Metaprogramming

C++ Template Metaprogramming C++ Template Metaprogramming Juan Pedro Bolívar Puente Ableton AG 16 May 2013 Agenda 1 Introduction 2 Concepts and techniques 3 Reasoning about metaprograms 4 Conclusions Agenda 1 Introduction 2 Concepts

More information

C++ Exception Handling 1

C++ Exception Handling 1 C++ Exception Handling 1 An exception is a problem that arises during the execution of a program. A C++ exception is a response to an exceptional circumstance that arises while a program is running, such

More information

Object-Oriented Programming for Scientific Computing

Object-Oriented Programming for Scientific Computing Object-Oriented Programming for Scientific Computing Traits and Policies Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de Summer Semester

More information

Distributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes

Distributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes Distributed Real-Time Control Systems Lecture 17 C++ Programming Intro to C++ Objects and Classes 1 Bibliography Classical References Covers C++ 11 2 What is C++? A computer language with object oriented

More information

Programming in C++: Assignment Week 8

Programming in C++: Assignment Week 8 Programming in C++: Assignment Week 8 Total Marks : 20 September 9, 2017 Question 1 Consider the following code segment. Mark 2 void myfunction(int test) { try { if (test) throw test; else throw "Value

More information

C++1z: Concepts-Lite !!! !!! !!!! Advanced Developer Conference C slides:

C++1z: Concepts-Lite !!! !!! !!!! Advanced Developer Conference C slides: C++1z: Concepts-Lite Advanced Developer Conference C++ 2014 slides: http://wiki.hsr.ch/petersommerlad/ Prof. Peter Sommerlad Director IFS Institute for Software Peter Sommerlad peter.sommerlad@hsr.ch Credo:

More information

Introduction to Programming

Introduction to Programming Introduction to Programming session 6 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Spring 2011 These slides are created using Deitel s slides Sharif University of Technology Outlines

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

Introduction to C++ with content from

Introduction to C++ with content from Introduction to C++ with content from www.cplusplus.com 2 Introduction C++ widely-used general-purpose programming language procedural and object-oriented support strong support created by Bjarne Stroustrup

More information

Implicit Evaluation of auto Variables and Arguments

Implicit Evaluation of auto Variables and Arguments Implicit Evaluation of auto Variables and Arguments Document number: N3748 Authors: Joël Falcou University Paris XI, LRI Peter Gottschling SimuNova Herb Sutter Microsoft Date: 2013-08-30 Project: Programming

More information

Expansion statements. Version history. Introduction. Basic usage

Expansion statements. Version history. Introduction. Basic usage Expansion statements Version history Document: P1306R0 Revises: P0589R0 Date: 08 10 2018 Audience: EWG Authors: Andrew Sutton (asutton@uakron.edu) Sam Goodrick (sgoodrick@lock3software.com) Daveed Vandevoorde

More information

Advanced Systems Programming

Advanced Systems Programming Advanced Systems Programming Introduction to C++ Martin Küttler September 19, 2017 1 / 18 About this presentation This presentation is not about learning programming or every C++ feature. It is a short

More information

@odinthenerd. not the god. Auto-Intern GmbH 1

@odinthenerd. not the god. Auto-Intern GmbH 1 @odinthenerd not the god Auto-Intern GmbH 1 Auto-Intern GmbH 2 You are awesome! I m not impressed Auto-Intern GmbH 3 You are awesome! I m not impressed Auto-Intern GmbH 4 You are awesome! I m not impressed

More information

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

Elevate your Code to Modern C++ with Automated Tooling. Peter Sommerlad Elevate your Code to Modern C++ with Automated Tooling Peter Sommerlad Simple C++ Less Code == More Software Know your language and its (modern) idioms Don t be afraid of STL or templates Start small.

More information

Reminder: compiling & linking

Reminder: compiling & linking Reminder: compiling & linking source file 1 object file 1 source file 2 compilation object file 2 library object file 1 linking (relocation + linking) load file source file N object file N library object

More information

Modern C++, From the Beginning to the Middle. Ansel Sermersheim & Barbara Geller ACCU / C++ November 2017

Modern C++, From the Beginning to the Middle. Ansel Sermersheim & Barbara Geller ACCU / C++ November 2017 Modern C++, From the Beginning to the Middle Ansel Sermersheim & Barbara Geller ACCU / C++ November 2017 1 Introduction Where is the Beginning Data Types References Const Const Const Semantics Templates

More information

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

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works Type Aliases A name may be defined as a synonym for an existing type name. Traditionally, typedef is used for this purpose. In the new standard, an alias declaration can also be used C++11.Thetwoformsareequivalent.

More information

About Codefrux While the current trends around the world are based on the internet, mobile and its applications, we try to make the most out of it. As for us, we are a well established IT professionals

More information

C++ Tutorial AM 225. Dan Fortunato

C++ Tutorial AM 225. Dan Fortunato C++ Tutorial AM 225 Dan Fortunato Anatomy of a C++ program A program begins execution in the main() function, which is called automatically when the program is run. Code from external libraries can be

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

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program Syntax What the Compiler needs to understand your program 1 Pre-Processing Any line that starts with # is a pre-processor directive Pre-processor consumes that entire line Possibly replacing it with other

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

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

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

CS3157: Advanced Programming. Outline

CS3157: Advanced Programming. Outline CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

eingebetteter Systeme

eingebetteter Systeme Praktikum: Entwicklung interaktiver eingebetteter Systeme C++-Tutorial (falk@cs.fau.de) 1 Agenda Classes Pointers and References Functions and Methods Function and Operator Overloading Template Classes

More information

Types, Values, Variables & Assignment. EECS 211 Winter 2018

Types, Values, Variables & Assignment. EECS 211 Winter 2018 Types, Values, Variables & Assignment EECS 211 Winter 2018 2 Road map Strings and string I/O Integers and integer I/O Types and objects * Type safety * Not as in object orientation we ll get to that much

More information

Programmazione. Prof. Marco Bertini

Programmazione. Prof. Marco Bertini Programmazione Prof. Marco Bertini marco.bertini@unifi.it http://www.micc.unifi.it/bertini/ Hello world : a review Some differences between C and C++ Let s review some differences between C and C++ looking

More information

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

CS11 Advanced C++ Fall Lecture 7

CS11 Advanced C++ Fall Lecture 7 CS11 Advanced C++ Fall 2006-2007 Lecture 7 Today s Topics Explicit casting in C++ mutable keyword and const Template specialization Template subclassing Explicit Casts in C and C++ C has one explicit cast

More information

A Crash Course in (Some of) Modern C++

A Crash Course in (Some of) Modern C++ CMPT 373 Software Development Methods A Crash Course in (Some of) Modern C++ Nick Sumner wsumner@sfu.ca With material from Bjarne Stroustrup & Herb Sutter C++ was complicated/intimidating Pointers Arithmetic

More information

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language Introduction C++ widely-used general-purpose programming language procedural and object-oriented support strong support created by Bjarne Stroustrup starting in 1979 based on C Introduction to C++ also

More information

15. Pointers, Algorithms, Iterators and Containers II

15. Pointers, Algorithms, Iterators and Containers II 498 Recall: Pointers running over the Array 499 Beispiel 15. Pointers, Algorithms, Iterators and Containers II int a[5] = 3, 4, 6, 1, 2; for (int p = a; p < a+5; ++p) std::cout

More information

Type Inference auto for Note: Note:

Type Inference auto for Note: Note: Type Inference C++11 provides mechanisms for type inference which make the compiler deduce the types of expressions. I m starting the book with type inference because it can make your code more concise

More information

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program: Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams

More information

C++ Template Meta. A basic introduction to basic C++ techniques used in template metaprogramming.

C++ Template Meta. A basic introduction to basic C++ techniques used in template metaprogramming. C++ Template Meta A basic introduction to basic C++ techniques used in template metaprogramming. Github Repo The presentation and all of the code are online on github, with an OSI license. github.com/zwimer/template-meta-tutorial

More information

C++14 Reflections Without Macros, Markup nor External Tooling

C++14 Reflections Without Macros, Markup nor External Tooling C++14 Reflections Without Macros, Markup nor External Tooling Metaprogramming Tricks for POD Types Antony Polukhin Boost libraries maintainer (DLL, LexicalCast, Any, TypeIndex, Conversion) + Boost.CircularBuffer,

More information

C The new standard

C The new standard C++11 - The new standard Lars Kühne Institut für Informatik Lehrstuhl für theoretische Informatik II Friedrich-Schiller-Universität Jena January 16, 2013 Overview A little bit of history: C++ was initially

More information

GridKa School 2013: Effective Analysis C++ Templates

GridKa School 2013: Effective Analysis C++ Templates 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

More information

Walther Zwart - Meeting C Clean Integral Code

Walther Zwart - Meeting C Clean Integral Code Walther Zwart - Meeting C++ 2018 Clean Integral Code About me walther.zwart@gmail.com > 30 years of programming 20 years of C++ 3rd time at MeetingCPP 5 years at Optiver About me About Optiver Market Maker

More information

10. Functions (Part 2)

10. Functions (Part 2) 10.1 Overloaded functions 10. Functions (Part 2) In C++, two different functions can have the same name if their parameters are different; either because they have a different number of parameters, or

More information

AIMS Embedded Systems Programming MT 2017

AIMS Embedded Systems Programming MT 2017 AIMS Embedded Systems Programming MT 2017 Object-Oriented Programming with C++ Daniel Kroening University of Oxford, Computer Science Department Version 1.0, 2014 Outline Classes and Objects Constructors

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

QUIZ How do we implement run-time constants and. compile-time constants inside classes?

QUIZ How do we implement run-time constants and. compile-time constants inside classes? QUIZ How do we implement run-time constants and compile-time constants inside classes? Compile-time constants in classes The static keyword inside a class means there s only one instance, regardless of

More information

Type Conversion. and. Statements

Type Conversion. and. Statements and Statements Type conversion changing a value from one type to another Void Integral Floating Point Derived Boolean Character Integer Real Imaginary Complex no fractional part fractional part 2 tj Suppose

More information

Source-Code Information Capture

Source-Code Information Capture Source-Code Information Capture Robert Douglas 2015-04-08 Document Number: N4417 followup to N4129 Date: 2015-04-08 Project: Programming Language C++ 1 Introduction Logging, testing, and invariant checking

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

C++11: 10 Features You Should be Using. Gordon R&D Runtime Engineer Codeplay Software Ltd.

C++11: 10 Features You Should be Using. Gordon R&D Runtime Engineer Codeplay Software Ltd. C++11: 10 Features You Should be Using Gordon Brown @AerialMantis R&D Runtime Engineer Codeplay Software Ltd. Agenda Default and Deleted Methods Static Assertions Delegated and Inherited Constructors Null

More information

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy CAAM 420 Fall 2012 Lecture 29 Duncan Eddy November 7, 2012 Table of Contents 1 Templating in C++ 3 1.1 Motivation.............................................. 3 1.2 Templating Functions........................................

More information

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

ME240 Computation for Mechanical Engineering. Lecture 4. C++ Data Types ME240 Computation for Mechanical Engineering Lecture 4 C++ Data Types Introduction In this lecture we will learn some fundamental elements of C++: Introduction Data Types Identifiers Variables Constants

More information

Structuur van Computerprogramma s 2

Structuur van Computerprogramma s 2 Structuur van Computerprogramma s 2 dr. Dirk Deridder Dirk.Deridder@vub.ac.be http://soft.vub.ac.be/ Vrije Universiteit Brussel - Faculty of Science and Bio-Engineering Sciences - Computer Science Department

More information

Database Systems on Modern CPU Architectures

Database Systems on Modern CPU Architectures Database Systems on Modern CPU Architectures Introduction to Modern C++ Moritz Sichert Technische Universität München Department of Informatics Chair of Data Science and Engineering Overview Prerequisites:

More information

CS302 - Data Structures using C++

CS302 - Data Structures using C++ CS302 - Data Structures using C++ Pre-Course: Variables, Basic Types, Control Structures Kostas Alexis Slides inspired by the course Modern C++, Uni Bonn: http://www.ipb.uni-bonn.de/teaching/modern-cpp/

More information

Chapter 2 - Control Structures

Chapter 2 - Control Structures Chapter 2 - Control Structures 1 Outline 2.1 Introduction 2.2 Algorithms 2.3 Pseudocode 2.4 Control Structures 2.5 if Selection Structure 2.6 if/else Selection Structure 2.7 while Repetition Structure

More information

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example CS 311 Data Structures and Algorithms Lecture Slides Friday, September 11, 2009 continued Glenn G. Chappell

More information

C++11/14 Rocks. Clang Edition. Alex Korban

C++11/14 Rocks. Clang Edition. Alex Korban C++11/14 Rocks Clang Edition Alex Korban 1 Contents Introduction 9 C++11 guiding principles... 9 Type Inference 11 auto... 11 Some things are still manual... 12 More than syntactic sugar... 12 Why else

More information

COMP322 - Introduction to C++

COMP322 - Introduction to C++ COMP322 - Introduction to C++ Winter 2011 Lecture 2 - Language Basics Milena Scaccia School of Computer Science McGill University January 11, 2011 Course Web Tools Announcements, Lecture Notes, Assignments

More information

Introduce C# as Object Oriented programming language. Explain, tokens,

Introduce C# as Object Oriented programming language. Explain, tokens, Module 2 98 Assignment 1 Introduce C# as Object Oriented programming language. Explain, tokens, lexicals and control flow constructs. 99 The C# Family Tree C Platform Independence C++ Object Orientation

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Lecture 8. Exceptions, Constructor, Templates TDDD86: DALP. Content. Contents Exceptions

Lecture 8. Exceptions, Constructor, Templates TDDD86: DALP. Content. Contents Exceptions Lecture 8 Exceptions, Constructor, Templates TDDD86: DALP Utskriftsversion av Lecture in Data Structures, Algorithms and Programming Paradigms 19th September 2017 Ahmed Rezine, IDA, Linköping University

More information