C++11 introduced many new features including type deduction with auto, uniform initialization syntax, rvalue references and move semantics, improved enums, lambda expressions, and smart pointers. Type deduction with auto lets the compiler deduce the type of a variable based on its initializer. Uniform initialization uses curly braces {} and allows narrowing conversions only if explicitly cast. Rvalue references and move semantics allow moving an object to avoid expensive copies by leaving the source object in a valid but unspecified state.
From ReactPHP to Facebook Hack's Async implementation and many more, asynchronous programming has been a 'hot' topic lately. But how well does async programming support work in PHP and what can you actually use it for in your projects ? Let's look at some real-world use cases and how they leverage the power of async to do things you didn't know PHP could do.
The document discusses various ways to extend and modify the Ruby parser. It covers:
1. Proposed syntax additions like {:key :-) "value"} and ++i which would require changes to the lexer and parser.
2. How the parser handles colons and symbols using token types like tCOLON2.
3. Examples of parsing constructs like method calls, assignments, and the def A#b syntax.
4. Details of how the lexer and parser are implemented in C using a parser generator and interaction between lexer states and token types.
The document discusses hacking the Ruby parser parse.y to add new syntax features to the Ruby language. It covers several cases:
1. Adding :-) as an alias for => in hash literals.
2. Treating single quotes as symbol literals under certain conditions.
3. Adding ++ as an incremental operator.
4. Parsing the A#b syntax for defining instance methods.
The document analyzes how parse.y and the lexer deal with colons, quotes, comments and other syntax elements, and shows the changes needed to parse the new syntax features. It also discusses Ruby internals like the parser generator bison, and MRI implementation details like the parse.y file size.
Swift is a new programming language introduced by Apple in 2014. It is designed to be more readable, require less code, and be safer than Objective-C. Some key differences include the use of variables instead of pointers, type inference, optionals to handle nil values, and generics. Swift uses structures, enums, and classes and supports features like closures and option chaining. Overall, Swift aims to blend the best of Objective-C, Rust, Haskell and other languages into a more modern, powerful and intuitive option for building apps for Apple platforms.
The document discusses various PHP programming concepts like variables, data types, operators, control structures, and functions. It provides code examples to demonstrate how to work with variables, different data types, operators, conditional statements, loops, and functions in PHP. Various PHP concepts covered include strings, arrays, objects, constants, arithmetic operators, comparison operators, if/else statements, switch statements, while loops, for loops, and functions.
Asynchronous operations are getting more and more popular. To the point that we are getting frameworks and environments revolving strictly around that concept. Boost.ASIO, Twisted and node.js are notable example. We will not explore that area. We will focus on techniques for making asynchronous more readable. We will present different currently used solutions. At the end we will introduce coroutines and explain the concept. We will show how these can be integrated with asynchronous code and what we benefit from using coroutines in asynchronous code.
The document discusses the Falcon programming language, noting its open source, simple, fast and powerful nature. It highlights features of Falcon like full support for multithreading, support for coroutines, and faster speed compared to Python. Examples are provided of Falcon's syntax for variables, data types, operators, functions, and control flow structures that are similar to other languages like C/C++ and Lua.
Paradigmas de Linguagens de Programacao - Aula #4Ismar Silveira
The document discusses different parameter passing techniques in programming languages, including pass by value, pass by reference, and pass by result/value-result. It provides examples in languages like C, C++, Java, C#, Pascal, Ada to illustrate how each technique works and the differences between them. It also covers topics like parameter modes (in, out, in-out), parameter arrays, and variable arguments.
From ReactPHP to Facebook Hack's Async implementation and many more, asynchronous programming has been a 'hot' topic lately. But how well does async programming support work in PHP and what can you actually use it for in your projects ? Let's look at some real-world use cases and how they leverage the power of async to do things you didn't know PHP could do.
The document discusses various ways to extend and modify the Ruby parser. It covers:
1. Proposed syntax additions like {:key :-) "value"} and ++i which would require changes to the lexer and parser.
2. How the parser handles colons and symbols using token types like tCOLON2.
3. Examples of parsing constructs like method calls, assignments, and the def A#b syntax.
4. Details of how the lexer and parser are implemented in C using a parser generator and interaction between lexer states and token types.
The document discusses hacking the Ruby parser parse.y to add new syntax features to the Ruby language. It covers several cases:
1. Adding :-) as an alias for => in hash literals.
2. Treating single quotes as symbol literals under certain conditions.
3. Adding ++ as an incremental operator.
4. Parsing the A#b syntax for defining instance methods.
The document analyzes how parse.y and the lexer deal with colons, quotes, comments and other syntax elements, and shows the changes needed to parse the new syntax features. It also discusses Ruby internals like the parser generator bison, and MRI implementation details like the parse.y file size.
Swift is a new programming language introduced by Apple in 2014. It is designed to be more readable, require less code, and be safer than Objective-C. Some key differences include the use of variables instead of pointers, type inference, optionals to handle nil values, and generics. Swift uses structures, enums, and classes and supports features like closures and option chaining. Overall, Swift aims to blend the best of Objective-C, Rust, Haskell and other languages into a more modern, powerful and intuitive option for building apps for Apple platforms.
The document discusses various PHP programming concepts like variables, data types, operators, control structures, and functions. It provides code examples to demonstrate how to work with variables, different data types, operators, conditional statements, loops, and functions in PHP. Various PHP concepts covered include strings, arrays, objects, constants, arithmetic operators, comparison operators, if/else statements, switch statements, while loops, for loops, and functions.
Asynchronous operations are getting more and more popular. To the point that we are getting frameworks and environments revolving strictly around that concept. Boost.ASIO, Twisted and node.js are notable example. We will not explore that area. We will focus on techniques for making asynchronous more readable. We will present different currently used solutions. At the end we will introduce coroutines and explain the concept. We will show how these can be integrated with asynchronous code and what we benefit from using coroutines in asynchronous code.
The document discusses the Falcon programming language, noting its open source, simple, fast and powerful nature. It highlights features of Falcon like full support for multithreading, support for coroutines, and faster speed compared to Python. Examples are provided of Falcon's syntax for variables, data types, operators, functions, and control flow structures that are similar to other languages like C/C++ and Lua.
Paradigmas de Linguagens de Programacao - Aula #4Ismar Silveira
The document discusses different parameter passing techniques in programming languages, including pass by value, pass by reference, and pass by result/value-result. It provides examples in languages like C, C++, Java, C#, Pascal, Ada to illustrate how each technique works and the differences between them. It also covers topics like parameter modes (in, out, in-out), parameter arrays, and variable arguments.
Python is a great language, but there are occasions where we need access to low level operations or connect with some database driver written in C. With the FFI(Foreign function interface) we can connect Python with other languages like C, C++ and even the new Rust. There are some alternatives to achieve this goal, Native Extensions, Ctypes and CFFI. I'll compare this three ways of extending Python.
This document provides tips, tricks, and examples of common gotchas in PHP programming. It demonstrates unexpected behaviors that can occur due to PHP's highly dynamic nature and weakly typed system. A series of code snippets are shown with their expected versus actual outputs to illustrate issues one may encounter with variables, strings, arrays, and type coercion. The document also provides best practices for PHP development and an overview of common topics covered in the PHP certification exam.
This document discusses how to use three C++17 vocabulary types: std::optional, std::variant, and std::any. It begins with an introduction and overview of the types. It then provides examples and explanations of how to create, access, and manipulate values for each type. Key points covered include initialization, accessing contained values, performance characteristics, and common use cases.
The document provides an overview of C++17's std::filesystem library. It introduces the Path class for representing file system paths, the DirectoryEntry class for modeling directory entries, and DirectoryIterator for iterating over directories. It also summarizes key support functions for querying and modifying files and directories, handling permissions, and catching errors and exceptions. Examples are provided demonstrating how to get a file size, iterate over a directory, and monitor a directory for changes using std::filesystem.
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHPGuilherme Blanco
The document provides an overview of Doctrine 2, an object-relational mapper (ORM) for PHP. It discusses the key components of Doctrine 2 including Common, DBAL, and ORM. Common includes cache drivers, class loading, collections, and annotations parsing functionality. DBAL provides a database abstraction layer built on PDO and supports drivers for databases like MySQL, PostgreSQL, SQLite. ORM provides object-relational mapping functionality to map database rows to PHP objects. The document also discusses performance comparisons showing Doctrine 2 can be faster than raw PHP for certain operations like inserts due to its use of transactions.
PHP 7 is scheduled for release in November 2015 and will be a major new version that introduces many new features and changes. Some key points include: PHP 7 will provide improved performance through a new Zend Engine 3.0 and full support for 32-bit and 64-bit platforms. New features include scalar type declarations, return type declarations, new operators like the null coalesce operator and the spaceship operator, and anonymous classes. The release will also change some behaviors and remove deprecated features.
1. The documents describe C programs that implement stacks using arrays, evaluate postfix expressions, convert infix to postfix notation, and check for balanced parentheses.
2. Key aspects include using structures to represent stacks, functions for push, pop, empty, full, and display operations on stacks.
3. The programs demonstrate using stacks to evaluate expressions by pushing operands and applying operators based on precedence.
The document discusses functions in C programming. It provides examples of defining functions with parameters and return types, calling functions by passing arguments, using header files to declare functions, and recursion. It shows functions being defined and called to perform tasks like calculating factorials, displaying prices based on hotel rates and nights, and converting numbers to binary. Functions allow breaking programs into smaller, reusable components.
This document summarizes the evolution of PHP from issues with early versions like inconsistent naming and unpredictable releases to recent improvements like namespaces, anonymous functions, and a standardized release cycle. It discusses tools for PHP development like Composer and FIG as well as educational resources. Key points covered include PHP's move to namespaces in 5.3, anonymous functions in 5.4, and built-in password hashing in 5.5. FIG standards like PSR-0 help code sharing while Composer eases dependency management.
The document provides guidance on how to write PHP extensions in C. It discusses compiling extensions, writing tests, handling data types, using object-oriented features like classes, and documenting extensions. Key steps include setting up the build environment, adding basic scaffolding, writing tests, getting and returning data, and releasing extensions on PECL. Advanced topics covered are globals, memory management, custom objects, and thread safety. The document aims to explain the full process for writing reliable and well-integrated PHP extensions.
4 operators, expressions & statementsMomenMostafa
This document discusses various C programming language concepts including operators, expressions, statements, data types, and type conversions. It provides examples of using unary and binary operators, increment/decrement operators, and the modulus operator. It also discusses operator precedence, expressions, statements, and how C handles type conversions between integers, floats, and characters both automatically and through explicit casting. Loops and conditional statements are demonstrated in examples converting seconds to minutes and counting down bottles of water.
This document discusses various ways to customize and extend PHP beyond its typical usage as a templating language. It explores how PHP's opcode cache, extensions, object model, and virtual machine can be leveraged. It also provides examples of PHP's lexer, parser, and how opcodes are generated from PHP code.
6 c control statements branching & jumpingMomenMostafa
This document discusses various C programming concepts including control statements, functions like getchar() and putchar(), character testing and mapping functions from ctype.h, nested if/else statements, the conditional operator, continue and break statements. It provides examples of using these concepts to analyze user input, manipulate characters, calculate electricity bills with rate tiers, check for prime numbers, and calculate statistics from scored entered by the user.
The document introduces some basic C++ idioms, rules, guidelines and best practices. The author notes that some items are based on their personal style preferences and the styles of groups they work with. The intention is to use the presentation to spark discussion, as it includes some controversial issues. Readers are encouraged to provide criticism of the example code presented.
sdlBasic is a basic interpreter that allows creating simple 2D games across multiple platforms like Linux, Windows, MacOS, and others. It uses the SDL library for graphics and allows working with sprites, sounds, user input and more. The interpreter was created by adapting and combining open source code distributed under licenses like GPL and LGPL.
Presented at Web Unleashed on September 16-17, 2015 in Toronto, Canada
More info at www.fitc.ca/webu
Why TypeScript?
with Jeff Francis
OVERVIEW
TypeScript is a type-checked superset of JavaScript that benefits medium-sized to complex JavaScript projects. Why would you want to learn a new language, instead of another JavaScript framework? You have all this existing JavaScript code, so how can you adopt something new without throwing the old stuff out?
This session is about the benefits of using TypeScript on top of JavaScript in your projects, and demonstrate step by step ways of migrating an existing JavaScript project to TypeScript. We will dive into code generated by the compiler and look at resources and tools that make working in TypeScript a pleasurable experience.
OBJECTIVE
To understand when it’s a good idea to use TypeScript.
TARGET AUDIENCE
JavaScript developers.
ASSUMED AUDIENCE KNOWLEDGE
Intermediate JavaScript experience.
FIVE THINGS AUDIENCE MEMBERS WILL LEARN
The basics of TypeScript – types, classes, modules, and functions
How TypeScript’s design makes getting started simple and helps projects
What compiled TypeScript looks like and how to debug
What tools can help take advantage of TypeScript’s type information
How to migrate a JavaScript project to TypeScript
This slides describes the basic concepts of industrial-strength compiler design. This includes basic concept of static single-assignment form (SSA) and various optimizations such as dead code elimination, global value numbering, constant propagation, etc. This is intend for a 150 minutes undergraduate compiler class.
This document provides an introduction to the Swift programming language presented by Giuseppe Arici and Matteo Battaglio. It covers the history and principles of Swift, highlighting that it is a modern, multi-paradigm language inspired by many other languages. The document then discusses key Swift concepts like constants and variables, functions and closures, tuples and pattern matching, classes and structs, protocols and extensions, generics and optionals. It encourages exploring these concepts through playgrounds and considers open questions around Swift's future and use in production environments.
The document discusses PHP performance and dives into the internals of how PHP works, including details on the Zend engine, compilation process involving lexing, parsing and compiling to opcodes, and execution through opcode interpretation by the virtual machine. It provides examples and tips on optimizing performance by reducing compilation overhead through opcode caching, profiling execution to find bottlenecks, and analyzing PHP functions at the C level to optimize system calls and memory usage.
C++17 introduced updates to both the C++ language and standard library. For the language, there were around 45 modest proposals that mostly solved frustrations from prior standards. Significant updates to the library included new vocabulary types like std::optional and std::string_view. C++17 also added features like structured bindings, if constexpr, and lambda improvements like constexpr lambdas and capture of *this. The filesystem library was standardized to provide OS-abstraction for file/directory operations.
10 Of The Best Books About TCP/IP And Networking
1.Internet Core Protocols: The Definitive Guide: Help for Network Administrators
2.Effective TCP/IP Programming: 44 Tips to Improve Your Network Programs
3.TCP/IP Explained
4.High-Speed Networks TCP/IP and ATM Design Principles
5.TCP/IP: Architecture, Protocols, and Implementation with IPv6 and IP
6.SNMP, SNMPv2, SNMPv3, and RMON 1 and 2
7.SNMP: A Guide to Network Management
8.TCP/IP Network Administration
9.Teach Yourself Tcp/Ip in 14 Days
10.UNIX Network Programming
Python is a great language, but there are occasions where we need access to low level operations or connect with some database driver written in C. With the FFI(Foreign function interface) we can connect Python with other languages like C, C++ and even the new Rust. There are some alternatives to achieve this goal, Native Extensions, Ctypes and CFFI. I'll compare this three ways of extending Python.
This document provides tips, tricks, and examples of common gotchas in PHP programming. It demonstrates unexpected behaviors that can occur due to PHP's highly dynamic nature and weakly typed system. A series of code snippets are shown with their expected versus actual outputs to illustrate issues one may encounter with variables, strings, arrays, and type coercion. The document also provides best practices for PHP development and an overview of common topics covered in the PHP certification exam.
This document discusses how to use three C++17 vocabulary types: std::optional, std::variant, and std::any. It begins with an introduction and overview of the types. It then provides examples and explanations of how to create, access, and manipulate values for each type. Key points covered include initialization, accessing contained values, performance characteristics, and common use cases.
The document provides an overview of C++17's std::filesystem library. It introduces the Path class for representing file system paths, the DirectoryEntry class for modeling directory entries, and DirectoryIterator for iterating over directories. It also summarizes key support functions for querying and modifying files and directories, handling permissions, and catching errors and exceptions. Examples are provided demonstrating how to get a file size, iterate over a directory, and monitor a directory for changes using std::filesystem.
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHPGuilherme Blanco
The document provides an overview of Doctrine 2, an object-relational mapper (ORM) for PHP. It discusses the key components of Doctrine 2 including Common, DBAL, and ORM. Common includes cache drivers, class loading, collections, and annotations parsing functionality. DBAL provides a database abstraction layer built on PDO and supports drivers for databases like MySQL, PostgreSQL, SQLite. ORM provides object-relational mapping functionality to map database rows to PHP objects. The document also discusses performance comparisons showing Doctrine 2 can be faster than raw PHP for certain operations like inserts due to its use of transactions.
PHP 7 is scheduled for release in November 2015 and will be a major new version that introduces many new features and changes. Some key points include: PHP 7 will provide improved performance through a new Zend Engine 3.0 and full support for 32-bit and 64-bit platforms. New features include scalar type declarations, return type declarations, new operators like the null coalesce operator and the spaceship operator, and anonymous classes. The release will also change some behaviors and remove deprecated features.
1. The documents describe C programs that implement stacks using arrays, evaluate postfix expressions, convert infix to postfix notation, and check for balanced parentheses.
2. Key aspects include using structures to represent stacks, functions for push, pop, empty, full, and display operations on stacks.
3. The programs demonstrate using stacks to evaluate expressions by pushing operands and applying operators based on precedence.
The document discusses functions in C programming. It provides examples of defining functions with parameters and return types, calling functions by passing arguments, using header files to declare functions, and recursion. It shows functions being defined and called to perform tasks like calculating factorials, displaying prices based on hotel rates and nights, and converting numbers to binary. Functions allow breaking programs into smaller, reusable components.
This document summarizes the evolution of PHP from issues with early versions like inconsistent naming and unpredictable releases to recent improvements like namespaces, anonymous functions, and a standardized release cycle. It discusses tools for PHP development like Composer and FIG as well as educational resources. Key points covered include PHP's move to namespaces in 5.3, anonymous functions in 5.4, and built-in password hashing in 5.5. FIG standards like PSR-0 help code sharing while Composer eases dependency management.
The document provides guidance on how to write PHP extensions in C. It discusses compiling extensions, writing tests, handling data types, using object-oriented features like classes, and documenting extensions. Key steps include setting up the build environment, adding basic scaffolding, writing tests, getting and returning data, and releasing extensions on PECL. Advanced topics covered are globals, memory management, custom objects, and thread safety. The document aims to explain the full process for writing reliable and well-integrated PHP extensions.
4 operators, expressions & statementsMomenMostafa
This document discusses various C programming language concepts including operators, expressions, statements, data types, and type conversions. It provides examples of using unary and binary operators, increment/decrement operators, and the modulus operator. It also discusses operator precedence, expressions, statements, and how C handles type conversions between integers, floats, and characters both automatically and through explicit casting. Loops and conditional statements are demonstrated in examples converting seconds to minutes and counting down bottles of water.
This document discusses various ways to customize and extend PHP beyond its typical usage as a templating language. It explores how PHP's opcode cache, extensions, object model, and virtual machine can be leveraged. It also provides examples of PHP's lexer, parser, and how opcodes are generated from PHP code.
6 c control statements branching & jumpingMomenMostafa
This document discusses various C programming concepts including control statements, functions like getchar() and putchar(), character testing and mapping functions from ctype.h, nested if/else statements, the conditional operator, continue and break statements. It provides examples of using these concepts to analyze user input, manipulate characters, calculate electricity bills with rate tiers, check for prime numbers, and calculate statistics from scored entered by the user.
The document introduces some basic C++ idioms, rules, guidelines and best practices. The author notes that some items are based on their personal style preferences and the styles of groups they work with. The intention is to use the presentation to spark discussion, as it includes some controversial issues. Readers are encouraged to provide criticism of the example code presented.
sdlBasic is a basic interpreter that allows creating simple 2D games across multiple platforms like Linux, Windows, MacOS, and others. It uses the SDL library for graphics and allows working with sprites, sounds, user input and more. The interpreter was created by adapting and combining open source code distributed under licenses like GPL and LGPL.
Presented at Web Unleashed on September 16-17, 2015 in Toronto, Canada
More info at www.fitc.ca/webu
Why TypeScript?
with Jeff Francis
OVERVIEW
TypeScript is a type-checked superset of JavaScript that benefits medium-sized to complex JavaScript projects. Why would you want to learn a new language, instead of another JavaScript framework? You have all this existing JavaScript code, so how can you adopt something new without throwing the old stuff out?
This session is about the benefits of using TypeScript on top of JavaScript in your projects, and demonstrate step by step ways of migrating an existing JavaScript project to TypeScript. We will dive into code generated by the compiler and look at resources and tools that make working in TypeScript a pleasurable experience.
OBJECTIVE
To understand when it’s a good idea to use TypeScript.
TARGET AUDIENCE
JavaScript developers.
ASSUMED AUDIENCE KNOWLEDGE
Intermediate JavaScript experience.
FIVE THINGS AUDIENCE MEMBERS WILL LEARN
The basics of TypeScript – types, classes, modules, and functions
How TypeScript’s design makes getting started simple and helps projects
What compiled TypeScript looks like and how to debug
What tools can help take advantage of TypeScript’s type information
How to migrate a JavaScript project to TypeScript
This slides describes the basic concepts of industrial-strength compiler design. This includes basic concept of static single-assignment form (SSA) and various optimizations such as dead code elimination, global value numbering, constant propagation, etc. This is intend for a 150 minutes undergraduate compiler class.
This document provides an introduction to the Swift programming language presented by Giuseppe Arici and Matteo Battaglio. It covers the history and principles of Swift, highlighting that it is a modern, multi-paradigm language inspired by many other languages. The document then discusses key Swift concepts like constants and variables, functions and closures, tuples and pattern matching, classes and structs, protocols and extensions, generics and optionals. It encourages exploring these concepts through playgrounds and considers open questions around Swift's future and use in production environments.
The document discusses PHP performance and dives into the internals of how PHP works, including details on the Zend engine, compilation process involving lexing, parsing and compiling to opcodes, and execution through opcode interpretation by the virtual machine. It provides examples and tips on optimizing performance by reducing compilation overhead through opcode caching, profiling execution to find bottlenecks, and analyzing PHP functions at the C level to optimize system calls and memory usage.
C++17 introduced updates to both the C++ language and standard library. For the language, there were around 45 modest proposals that mostly solved frustrations from prior standards. Significant updates to the library included new vocabulary types like std::optional and std::string_view. C++17 also added features like structured bindings, if constexpr, and lambda improvements like constexpr lambdas and capture of *this. The filesystem library was standardized to provide OS-abstraction for file/directory operations.
10 Of The Best Books About TCP/IP And Networking
1.Internet Core Protocols: The Definitive Guide: Help for Network Administrators
2.Effective TCP/IP Programming: 44 Tips to Improve Your Network Programs
3.TCP/IP Explained
4.High-Speed Networks TCP/IP and ATM Design Principles
5.TCP/IP: Architecture, Protocols, and Implementation with IPv6 and IP
6.SNMP, SNMPv2, SNMPv3, and RMON 1 and 2
7.SNMP: A Guide to Network Management
8.TCP/IP Network Administration
9.Teach Yourself Tcp/Ip in 14 Days
10.UNIX Network Programming
This document discusses various usability enhancements introduced in modern C++, including C++11/14/17. It covers topics such as auto type deduction, decltype, nullptr, range-based for loops, uniform initialization, lambda expressions, and more. The enhancements aim to improve code readability, reduce errors and increase developer productivity when programming in C++.
The document provides an overview of Bjarne Stroustrup's views on the C++ programming language. Some key points:
1) C++ aims to provide performance, predictability, teachability, and readability while supporting systems programming, embedded systems, large systems, and both experts and novices.
2) C++ offers features like mapping to hardware, classes, inheritance, templates, and generic programming while not requiring a garbage collector for resource management.
3) Resource management in C++ relies on resource handles, RAII, and move semantics rather than a garbage collector. Templates and generic programming are designed to be as efficient and well-specified as traditional code.
This document provides an overview of new features introduced in C++11, including automatic variables, decltype, rvalue references, lambda functions, variadic templates, and the concurrency library. It discusses each feature in detail and provides examples. It also outlines compiler support for C++11 in different versions of Visual Studio and references additional learning resources on C++11.
The new standard for C++ language has been signed in 2011. This new (extended) language, called C++11, has a number of new semantics (in terms of language constructs) and a number of new standard library support. The major language extensions are discussed in this presentation. The library will be taken up in a later presentation.
The document is a tutorial on C++11 concurrency features such as asynchronous tasks, threads, promises, mutexes, and condition variables. It covers topics like spawning asynchronous tasks using std::async and std::thread, returning values from asynchronous tasks, passing parameters, handling exceptions, manually setting futures using std::promise and std::packaged_task, waiting for multiple futures, and using mutexes and lock guard templates for synchronization. Code examples are provided to illustrate the various concurrency features.
Este documento presenta un algoritmo basado en optimización por colonia de hormigas para detectar el clique (subgrafo completo) con la mayor interconectividad en un grafo. El algoritmo imita el comportamiento de las hormigas al depositar y evaporar feromonas a lo largo de los caminos para guiar la búsqueda hacia cliques óptimos. Los experimentos muestran que el algoritmo puede encontrar el clique máximo conocido en un grafo completo de 100 nodos.
The Goal and The Journey - Turning back on one year of C++14 MigrationJoel Falcou
C++14 has been announced as the next best thing since sliced bread in terms of simplicity, performance and overall elegance of c++ code. This talk is the story of why and how we decided to migrate one of our old 'modern C++' software library -- BSP++, a C++ implementation of the BSP parallel programming model -- to C++14.
More than just a recollection of 'use this' or 'do that' mottos, this talk will try to ponder on :
why one should consider migrating to C++14 now
which features actually helped and which one did not
the traps and pitfalls compilers tried to pull on us
The document provides instructions for a lesson on using sports vocabulary in the present continuous tense to describe what is happening in a park. It includes a vocabulary list of sports terms like jump, run, throw, and kick. It reviews the structure of the present continuous, including affirmative, negative, and interrogative forms. Students then listen to a description of a park by Andrew and answer questions to practice using the tense.
This document discusses C++11/14 enhancements including data types, literals, attributes, loops, constants, enumerations, typedefs, pointers, smart pointers, references, type inference, functions, and lambda expressions. It provides examples and explanations of new features in each category.
"Http protocol and other stuff" by Bipin UpadhyayBipin Upadhyay
A holistic view of how the web works, with an overview of the HTTP protocol.
Presented by me at null security group (http://null.co.in), Mumbai chapter meet on Aug' 27th.
The HTTP protocol is an application-level protocol used for distributed, collaborative, hypermedia information systems. It operates as a request-response protocol between clients and servers, with clients making requests using methods like GET and POST and receiving responses with status codes. Requests and responses are composed of text-based headers and messages to communicate metadata and content. Caching and cookies can be used to improve performance and maintain state in this otherwise stateless protocol.
The document discusses the history and development of the internet over the past 50 years, from its origins as a network created by the United States Department of Defense to support research and education, to its subsequent commercialization and global adoption driven by the creation of the World Wide Web in the early 1990s. It grew exponentially from being used primarily by academic and military institutions to becoming integrated into the daily lives of billions of people worldwide for communication, education, commerce, and entertainment.
Networking - TCP/IP stack introduction and IPv6Rodolfo Kohn
The document discusses IPv6 and Mobile IPv6 fundamentals, new services, and applications. It begins with an introduction to TCP/IP and the Internet and then covers the OSI and TCP/IP reference models. It describes the physical, data link, network, transport, and application layers. It focuses on IPv6 features like addressing, autoconfiguration, and mobility support through Mobile IPv6. It also discusses new applications and challenges with the transition from IPv4 to IPv6.
SIMD extensions have been a feature of choice for processor manufacturers for a couple of decades. Designed to exploit data parallelism in applications at the instruction level, these extensions still require a high level of expertise or the use of potentially fragile compiler support or vendor-specific libraries. While a large fraction of their theoretical accelerations can be obtained using such tools, exploiting such hardware becomes tedious as soon as application portability across hardware is required.
Accessing such capabilities directly from C++ code could be a major improvements in a lot of use cases. Different take on this has been proposed either by the community or as an actual standard proposal. Solutions include pragma based annotations, standard algorithms policies, full blown compiler support and libraries.
In this talk we will present one such solution - the Boost.SIMD library (currently being proposed as such) which takes a library approach to this issues.
We will go over the basic notion required to grasp SIMD programming in general. Then, we'll discuss the different existing approaches. We will describe Boost.SIMD API and API design to demonstrate how it solves issues raised by the actual idiomatic way of writting SIMD enabled code. Design issues like standard algorithm integration, memory handling and how to fill the gaps in SIMD instructions sets will be discussed. Finally, we show its performances with respect to a subset of well known benchmarks.
Database connectivity to sql server asp.netHemant Sankhla
This ppt will help those who are beginner in sql server, asp.net and C# and want to learn database connectivity. So i provide them the simpler code on this universe for their database enabled web or desktop application.
Este documento presenta el trabajo de titulación de dos estudiantes de ingeniería química de la Universidad de Guayaquil sobre la aplicación de las operaciones unitarias de lixiviación y destilación para obtener sustratos a partir de la albahaca y cuantificar su poder antioxidante. El documento incluye agradecimientos, dedicatorias, derechos de autoría y certificación del tutor. También presenta un resumen del trabajo, palabras clave y objetivos del estudio.
The document discusses C++0x standard library extensions (TR1) and advanced C++ techniques. It provides an overview of new features in C++0x related to the core language like type inference, lambda functions, and rvalue references. It also discusses changes to the C++ standard library like tuples, hash tables, smart pointers, and other containers. The document is intended as course material covering these new C++0x features.
The document discusses replacing OutputIterators in the C++ standard library with unary functions. It provides examples of how algorithms like copy, set_union, and set_intersection could be updated to take unary functions instead of OutputIterators. It also describes the OvenToBoost project, which aims to port range adaptors from the Oven library to Boost.Range to address limitations in Boost.Range and make it more useful like Oven. This includes adding things like taken, dropped, elements, and iteration adaptors and allowing ranges to work with lambdas. The status of the OvenToBoost project is that primary implementation and testing is complete but documentation remains outstanding.
Functions And Header Files In C++ | Bjarne stroustrupSyedHaroonShah4
This document discusses functions and header/source files in C++. It covers declarations, definitions, and the differences between them. Declarations introduce names and specify types, while definitions also fully specify the entity. Declarations allow interfaces to be specified. Headers contain declarations to share interfaces between parts of a program. Functions are described as units of operation that can take parameters and return values. The document also discusses scopes, namespaces, and storage classes like static.
This document provides an introduction to object-oriented programming concepts in C++ including objects, classes, encapsulation, inheritance, polymorphism, and more. It explains the basic structure of a C++ program and demonstrates how to write a simple "Hello World" program. It also covers basic C++ elements like variables, data types, comments, strings, arithmetic operators, and input/output.
This document provides an overview of key concepts for using the Arduino environment including board type, serial ports, parts of a sketch like setup and loop functions, variables, data types, operators, conditional statements, and repetition structures like for and while loops. Comments, pin modes, and interrupts are also introduced. The document explains syntax and provides examples to demonstrate how these concepts work together in Arduino code.
This document provides an overview of the Arduino environment and programming basics. It covers topics like board type, serial communication, parts of a sketch like setup and loop functions, variables, data types, operators, conditional statements, and repetition structures like for and while loops. Comments are also discussed as a way to annotate code. The document serves as an introduction for programmers new to Arduino.
This document provides an introduction to C++ programming concepts including variables, data types, constants, and I/O streams. It discusses basic C++ code structure and comments. Integral data types like char, bool, and integers are explained. Floating point types float and double are also introduced. The document demonstrates declaring and initializing variables as well as basic math operations on variables. Constants and the const keyword are described along with the #define preprocessor directive.
The document provides an overview of file structure and basic input/output in C++. It explains common elements like #include directives, namespaces, main functions, and variables. It also covers conditional statements, loops, and input/output streams for basic console applications.
This document provides an overview of the Swift programming language. It discusses Swift's history, principles, syntax, tools and practices. The history section notes that Chris Lattner created Swift at Apple in 2010 and that it was influenced by many other languages. The principles section states that Swift is imperative, functional, object-oriented, static, strongly typed and type safe. The document then covers Swift's syntax including basic syntax, functions and closures, data types, and control flows.
This document provides an overview of memory management concepts in Java and C++, including pointers, the heap, stack, activation records, classes and objects. It discusses how objects are allocated in memory in both languages, with objects in Java being referenced by pointers on the stack and allocated on the heap, while in C++ objects can be allocated on the stack or heap. The document also covers issues like memory leaks in C++ if objects are not deleted from the heap, and garbage collection handling object deletion in Java. Methods and calling conventions are compared between the two languages.
RailswayCon 2010 - Dynamic Language VMsLourens Naudé
The document discusses Ruby virtual machines and optimizations. It covers topics like Ruby VM internals, system resources, Ruby optimizations like constant folding and inlining, object structures, classes and modules, method dispatch, garbage collection. The goal is to understand tools and techniques for building high performance Ruby applications.
Scope and Closures in JavaScript
I have made a YouTube video on this topic. So, please feel free to click on the link below to better understand JavaScript.
Video Link: https://www.youtube.com/watch?v=PJJ5qAcNlwQ&list=PL0yG7EPFn4R8lmhfP36cV-G9nx6CEBewo
Rust LDN 24 7 19 Oxidising the Command LineMatt Provost
The document discusses various techniques for building command line utilities in Rust, including handling broken pipes, reading input byte-by-byte or line-by-line, reading from stdin or files, and handling non-UTF8 arguments. It provides code examples of reading from stdin, handling broken pipes gracefully, and collecting command line arguments as OsStrings to support non-UTF8 values. The document concludes by advertising open jobs at Yelp and providing contact information.
NetPonto - The Future Of C# - NetConf EditionPaulo Morgado
The document discusses various new features in C# and .NET, including:
- Async Main method allowing async entry points
- Inferred tuple element names for cleaner tuple syntax
- Default literal expressions avoiding unnecessary casts
- Non-trailing named arguments for more flexible calling syntax
- Pattern matching and switch expressions for more control flows
- Reference semantics for value types for improved performance
- And more proposals still in development like nullable reference types, ranges, and patterns.
It also provides links to documentation and code repositories for further reading.
Basic Introduction to programming functions, Contents include.
- Definition of function
- Structure of function
- Function calling
- Function Prototyping
- Scope of the function
- Input parameters to a function
- Returning from the function
- Types of function calling
The document provides an overview of the Swift programming language, summarizing that it is fast, modern, and safe. It then covers key Swift concepts like variables, strings, arrays, dictionaries, optionals, control flow, functions, closses, classes, inheritance, enums, structs, protocols, extensions, and generics in under 3 sentences each. The document encourages learning more about Swift from Apple's official documentation.
The document defines a class called ofBlob that represents a circle object that can be drawn and manipulated. It includes private variables to store the blob's position, dimension, speed, and phase. Methods are defined to initialize the blob, set/get its properties, update its position, and draw it. A testApp class is also defined that initializes a vector of ofBlob objects and calls their update and draw methods in a loop.
Gitlab - Creating C++ applications with Gitlab CIUilian Ries
Gitlab is a complete tool that integrates everything from project management to product construction. In this talk I will present how a C ++ project can be analyzed, built, tested and deployed using Gitlab.
Conan.io - The C/C++ package manager for DevelopersUilian Ries
Conan is a decentralized package manager for C and C++ that handles both source code and pre-compiled binaries. It addresses issues with building dependencies from source by allowing developers to define packages through recipes that specify dependencies and build instructions. Conan packages are cached locally and identified by name, version, and user/channel to allow isolation of builds. The Conan community contributes package recipes through open source projects on GitHub like the Conan Center and Bincrafters organization.
O documento discute diferentes fluxos de trabalho no Git como Gitflow, Github Flow e Gitlab Flow. Ele também fornece boas práticas como fazer commits pequenos e frequentes, usar branches, testar antes de commitar e escrever boas mensagens de commit. O documento recomenda adotar um fluxo de trabalho consistente e usar o controle de versão para compartilhamento de código, não como sistema de backup.
O documento apresenta os conceitos e práticas do Behavior Driven Development (BDD). O BDD enfatiza a colaboração entre times de negócios, desenvolvimento e teste para definir exemplos de comportamento do software. O BDD utiliza linguagens como Gherkin e ferramentas como Cucumber para documentar e automatizar casos de teste de aceitação com foco no valor para o negócio. O documento também discute desafios e benefícios da abordagem BDD.
This document summarizes a presentation about the Conan package manager for C and C++ applications. It discusses popular C++ libraries that are commonly needed like Boost and Poco. It shows how Conan can be used to add these libraries as dependencies to a project without needing to build them manually. The document provides an example of using Conan to add Boost and Poco to a demo application that calculates an MD5 hash and validates an email address. It also gives an overview of how Conan works, including its package naming scheme, local caching of packages, and community around sharing packages on Bintray.
O documento discute as bibliotecas POCO C++. A POCO é uma coleção de bibliotecas C++ portáteis focadas em redes e aplicações. Ela fornece funcionalidades como cache, processos, sistema de arquivos, aplicações, rede, notificações e manipulação de strings. A POCO é uma alternativa à biblioteca Boost e possui vantagens como ser mais compreensível e fornecer suporte a pontos não cobertos pela Boost, como SQLite e monitoramento de diretórios.
Conan is a C/C++ package manager that allows defining and consuming packages from source code or pre-compiled binaries. It supports dependency management, configuration, and testing of C/C++ projects. The document provides an example of using Conan to retrieve and link to the Poco networking library in a C++ project, and describes how to create, test, and publish Conan packages from source code.
This document discusses various software development tools for C/C++ projects including source control tools like Git and SVN, build tools for C++, frameworks for C/C++, code review of source code, unit testing and behavior driven development (BDD) testing, static and runtime code analysis, documentation tools, continuous integration for building and deploying, local and remote development environments, and solutions for local development, remote servers, continuous integration, and a datacom case study.
O documento discute o uso de frameworks de teste unitário GTest e Catch no C++, comparando suas funcionalidades, instalação e construção. É apresentada uma motivação para testes unitários e exemplos de código para ambos frameworks, destacando-se que GTest fornece recursos adicionais como geração de relatórios XML enquanto Catch é header-only.
O documento propõe desenvolver um sistema IoT para gerenciar sensores ambientais em um aquário ornamental e compartilhar dados online. O objetivo é automatizar tarefas de tratamento e apresentar estatísticas. A metodologia usará MQTT. O cronograma inclui definição do tema, levantamento bibliográfico, projeto do sistema embarcado, integração com IoT e apresentação final.
Mobile App Development Company In Noida | Drona InfotechDrona Infotech
Looking for a reliable mobile app development company in Noida? Look no further than Drona Infotech. We specialize in creating customized apps for your business needs.
Visit Us For : https://www.dronainfotech.com/mobile-application-development/
Flutter is a popular open source, cross-platform framework developed by Google. In this webinar we'll explore Flutter and its architecture, delve into the Flutter Embedder and Flutter’s Dart language, discover how to leverage Flutter for embedded device development, learn about Automotive Grade Linux (AGL) and its consortium and understand the rationale behind AGL's choice of Flutter for next-gen IVI systems. Don’t miss this opportunity to discover whether Flutter is right for your project.
Utilocate offers a comprehensive solution for locate ticket management by automating and streamlining the entire process. By integrating with Geospatial Information Systems (GIS), it provides accurate mapping and visualization of utility locations, enhancing decision-making and reducing the risk of errors. The system's advanced data analytics tools help identify trends, predict potential issues, and optimize resource allocation, making the locate ticket management process smarter and more efficient. Additionally, automated ticket management ensures consistency and reduces human error, while real-time notifications keep all relevant personnel informed and ready to respond promptly.
The system's ability to streamline workflows and automate ticket routing significantly reduces the time taken to process each ticket, making the process faster and more efficient. Mobile access allows field technicians to update ticket information on the go, ensuring that the latest information is always available and accelerating the locate process. Overall, Utilocate not only enhances the efficiency and accuracy of locate ticket management but also improves safety by minimizing the risk of utility damage through precise and timely locates.
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j
Dr. Jesús Barrasa, Head of Solutions Architecture for EMEA, Neo4j
Découvrez les dernières innovations de Neo4j, et notamment les dernières intégrations cloud et les améliorations produits qui font de Neo4j un choix essentiel pour les développeurs qui créent des applications avec des données interconnectées et de l’IA générative.
Do you want Software for your Business? Visit Deuglo
Deuglo has top Software Developers in India. They are experts in software development and help design and create custom Software solutions.
Deuglo follows seven steps methods for delivering their services to their customers. They called it the Software development life cycle process (SDLC).
Requirement — Collecting the Requirements is the first Phase in the SSLC process.
Feasibility Study — after completing the requirement process they move to the design phase.
Design — in this phase, they start designing the software.
Coding — when designing is completed, the developers start coding for the software.
Testing — in this phase when the coding of the software is done the testing team will start testing.
Installation — after completion of testing, the application opens to the live server and launches!
Maintenance — after completing the software development, customers start using the software.
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppGoogle
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-fusion-buddy-review
AI Fusion Buddy Review: Key Features
✅Create Stunning AI App Suite Fully Powered By Google's Latest AI technology, Gemini
✅Use Gemini to Build high-converting Converting Sales Video Scripts, ad copies, Trending Articles, blogs, etc.100% unique!
✅Create Ultra-HD graphics with a single keyword or phrase that commands 10x eyeballs!
✅Fully automated AI articles bulk generation!
✅Auto-post or schedule stunning AI content across all your accounts at once—WordPress, Facebook, LinkedIn, Blogger, and more.
✅With one keyword or URL, generate complete websites, landing pages, and more…
✅Automatically create & sell AI content, graphics, websites, landing pages, & all that gets you paid non-stop 24*7.
✅Pre-built High-Converting 100+ website Templates and 2000+ graphic templates logos, banners, and thumbnail images in Trending Niches.
✅Say goodbye to wasting time logging into multiple Chat GPT & AI Apps once & for all!
✅Save over $5000 per year and kick out dependency on third parties completely!
✅Brand New App: Not available anywhere else!
✅ Beginner-friendly!
✅ZERO upfront cost or any extra expenses
✅Risk-Free: 30-Day Money-Back Guarantee!
✅Commercial License included!
See My Other Reviews Article:
(1) AI Genie Review: https://sumonreview.com/ai-genie-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
#AIFusionBuddyReview,
#AIFusionBuddyFeatures,
#AIFusionBuddyPricing,
#AIFusionBuddyProsandCons,
#AIFusionBuddyTutorial,
#AIFusionBuddyUserExperience
#AIFusionBuddyforBeginners,
#AIFusionBuddyBenefits,
#AIFusionBuddyComparison,
#AIFusionBuddyInstallation,
#AIFusionBuddyRefundPolicy,
#AIFusionBuddyDemo,
#AIFusionBuddyMaintenanceFees,
#AIFusionBuddyNewbieFriendly,
#WhatIsAIFusionBuddy?,
#HowDoesAIFusionBuddyWorks
DDS Security Version 1.2 was adopted in 2024. This revision strengthens support for long runnings systems adding new cryptographic algorithms, certificate revocation, and hardness against DoS attacks.
E-commerce Application Development Company.pdfHornet Dynamics
Your business can reach new heights with our assistance as we design solutions that are specifically appropriate for your goals and vision. Our eCommerce application solutions can digitally coordinate all retail operations processes to meet the demands of the marketplace while maintaining business continuity.
Software Engineering, Software Consulting, Tech Lead, Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Transaction, Spring MVC, OpenShift Cloud Platform, Kafka, REST, SOAP, LLD & HLD.
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...kalichargn70th171
A dynamic process unfolds in the intricate realm of software development, dedicated to crafting and sustaining products that effortlessly address user needs. Amidst vital stages like market analysis and requirement assessments, the heart of software development lies in the meticulous creation and upkeep of source code. Code alterations are inherent, challenging code quality, particularly under stringent deadlines.
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Crescat
Crescat is industry-trusted event management software, built by event professionals for event professionals. Founded in 2017, we have three key products tailored for the live event industry.
Crescat Event for concert promoters and event agencies. Crescat Venue for music venues, conference centers, wedding venues, concert halls and more. And Crescat Festival for festivals, conferences and complex events.
With a wide range of popular features such as event scheduling, shift management, volunteer and crew coordination, artist booking and much more, Crescat is designed for customisation and ease-of-use.
Over 125,000 events have been planned in Crescat and with hundreds of customers of all shapes and sizes, from boutique event agencies through to international concert promoters, Crescat is rigged for success. What's more, we highly value feedback from our users and we are constantly improving our software with updates, new features and improvements.
If you plan events, run a venue or produce festivals and you're looking for ways to make your life easier, then we have a solution for you. Try our software for free or schedule a no-obligation demo with one of our product specialists today at crescat.io
2. AGENDA
•Why should I learn about C++11?
•C++11 Features
•deduction of a type from an initializer
•the type of an expression
•Initializer-list and uniform initialization
•rvalue references and move semantics
•static assertions
•preventing exception propagation
•override controls
•scoped and strongly typed enums
•lambda expressions
•defaulted and deleted functions
•smart pointers
•standard container array
3. WHY SHOULD I LEARN ABOUT C++11?
fonte: https://isocpp.org/files/img/wg21-timeline.png
4. WHY SHOULD I LEARN ABOUT C++11?
“C++11 feels like a new language” - Bjarne Stroustrup
5. DEDUCTION OF A TYPE FROM AN INITIALIZER
// C++98
std::map<std::string, std::vector<int, int> >::iterator it = foo.begin();
Singleton& singleton = Singleton::instance();
int bar;
// C++11
auto it = std::begin(foo);
auto& singleton = Singleton::instance();
auto bar; // error: declaration has no initializer
auto bar = 0;
6. DEDUCTION OF A TYPE FROM AN INITIALIZER
// C++98
std::vector<std::string>::const_iterator it;
for (it = strings.begin(); it != strings.end(); ++it) { /*...*/ }
// C++11
for (auto it : strings) { /*...*/ }
7. DEDUCTION OF A TYPE FROM AN INITIALIZER
// C++11
auto sum(int a, int b) -> int
{
return a + b;
}
template<typename Builder>
void buildAndProcess(Builder& builder)
{
auto baz = builder.Build();
baz.work();
}
8. DEDUCTION OF A TYPE FROM AN INITIALIZER
// C++11
template<typename Builder>
auto buildAndProcess(Builder& builder) -> ???
{
auto baz = builder.Build();
baz.work();
return baz;
}
9. THE TYPE OF AN EXPRESSION
•decltype
•Auto lets you declare a variable with a particular type
• decltype lets you extract the type from a variable (or any other
expression)
10. THE TYPE OF AN EXPRESSION
// C++11
int bar = 42;
decltype(bar) qux = bar;
auto qux = bar; // same
int qux();
decltype(qux()); // int
11. DEDUCTION OF A TYPE FROM AN INITIALIZER
// C++11
template<typename Builder>
auto buildAndProcess(Builder& builder) -> decltype( builder.Build() )
{
auto baz = builder.Build();
baz.work();
return baz;
}
// C++14
template<typename Builder>
auto buildAndProcess(Builder& builder)
{
auto baz = builder.Build();
baz.work();
return baz;
}
12. DEDUCTION OF A TYPE FROM AN INITIALIZER
#include <iostream>
struct Foo {
Foo () { std::cout << 1; }
~Foo() { std::cout << 3; }
void print() { std::cout << 2; }
};
int main() {
Foo foo[3];
for (auto it : foo) { it.print(); }
return 0;
}
fonte: http://ideone.com/ux5CeG for (auto& it : foo) { it.print(); }
13. DEDUCTION OF A TYPE FROM AN INITIALIZER
// C++11
int& bar();
auto foo = bar(); // int or int& ?
/* auto defaults to being by-value for references */
auto& foo = bar(); // int&
int* foo = new int(5);
auto bar = foo; // bar is int*
auto* qux = foo; // as before
14. DEDUCTION OF A TYPE FROM AN INITIALIZER
std::string foo("foo");
unsigned size = foo.size(); // type shortcut
std::string::size_type size = foo.size(); // official return type
auto size = foo.size(); // correct deduction
15. DEDUCTION OF A TYPE FROM AN INITIALIZER
// C++11
#include <unordered_map>
std::unordered_map<std::string, std::string> bar;
// bar receives some elements ...
for (const std::pair<std::string, std::string>& it : bar) { /* ... */ }
for (const auto& it : bar) { /* ... */ }
16. DEDUCTION OF A TYPE FROM AN INITIALIZER
•Things to remember:
•auto must be initialized;
•the compiler can evaluates better than you;
•auto can simplify your expression;
•a function can return auto type;
•a function parameter can be auto type (C++14);
•auto defaults to being by-value for references.
18. INITIALIZER-LIST AND UNIFORM INITIALIZATION
#include <iostream>
#include <initializer_list>
struct Foo {
Foo(int a, int b) { std::cout << a << " " << b << std::endl;
}
Foo (std::initializer_list<int> list) {
for (auto it : list) { std::cout << it << std::endl; }
}
};
int main() {
Foo foo{1, 2};
Foo foobar(1, 2);
return 0;
}
19. INITIALIZER-LIST AND UNIFORM INITIALIZATION
// C++98
int foo = 5.2; // narrowing convertion
int bar(3.14); // narrowing convertion
// C++11
int foo{5.2}; // error: narrowing convertion
int qux[3]{1, 2, 3};
std::vector<char> baz{'a', 'b', 'c'};
// C++98
Baz::Baz(int bar, int corge) : bar_(bar), corge_(corge) {}
insert_vlan( vlan(100, TAGGED) );
// C++11
Baz::Baz(int bar, int corge) : bar_{bar}, corge_{corge} {}
insert_vlan( {100, TAGGED} );
20. INITIALIZER-LIST AND UNIFORM INITIALIZATION
•initializer-list
•array of objects of type const T;
•must be homogeneous;
•immutable sequence.
std::initializer_list<int> qux{1, 2, 3, 4, 5}; // Okay
std::initializer_list<int> qux{1, 2, 3.0, 4, 5}; // NOK!
error: narrowing conversion of '3.0e+0' from 'double' to 'int'
inside { } [-Wnarrowing]
std::initializer_list<int> qux{1, 2, 3, 4, 5};
*qux.begin() = 42;
error: assignment of read-only location
21. INITIALIZER-LIST AND UNIFORM INITIALIZATION
#include <iostream>
#include <type_traits>
int main() {
auto foo{5};
auto bar = {3, 5};
auto qux{4, 2};
std::cout << std::is_integral<decltype(foo)>::value;
std::cout << std::is_integral<decltype(bat)>::value;
std::cout << std::is_integral<decltype(qux)>::value;
return 0;
}
fonte: http://ideone.com/QMhxvv
auto foo = 5;
error: direct-list-initialization of 'auto'
requires exactly one element [-
fpermissive] auto qux{4, 2};
22. RVALUE REFERENCES AND MOVE SEMANTICS
•In C++11, there are rvalues and lvalues:
•lvalues is an expression that could be the left hand side of an
assignment;
•rvalues is an expression that could be the right hand side of an
assignment;
int foo = 42; // foo is a lvalue; 42 is an rvalue
23. RVALUE REFERENCES AND MOVE SEMANTICS
•References:
•lvalue reference is formed by placing an & after some type;
•rvalue reference is formed by placing an && after some type;
int bar = 42; // bar is a lvalue
int& bar_ref = bar; // bar_ref is a lvalue reference
int& baz = 42; // error: can't bind rvalue
const int& baz = 42; // okay! baz is const reference
int&& qux = 42; // qux is an rvalue reference
qux = 54; // okay! can replace
int&& corge = bar; // error: can't bind lvalue
24. RVALUE REFERENCES AND MOVE SEMANTICS
•Why would we want to do this?:
•move semantics;
•perfect forward;
25. RVALUE REFERENCES AND MOVE SEMANTICS
•Move semantics
•replaces expansive copy with less expansive move;
•enables the creation of move-only type as unique_ptr;
•Consider:
template <class T>
swap(T& a, T& b)
{
T tmp(a); // now we have two copies of a
a = b; // now we have two copies of b
b = tmp; // now we have two copies of tmp (aka a)
}
26. RVALUE REFERENCES AND MOVE SEMANTICS
#include <utility>
template <class T>
swap(T& a, T& b)
{
T tmp(std::move(a)); // move a contents to tmp; a is empty
a = std::move(b); // move b contents to a; b is empty
b = std::move(tmp); // move tmp contents to b; tmp is empty
}
•move gives its target the value of its argument, but is not
obliged to preserve the value of its source;
•if move is not possible, then the value will be copied.
27. RVALUE REFERENCES AND MOVE SEMANTICS
class Foo { // Temporary
Object
std::string bar;
public:
Foo(const std::string& ss) : bar(ss) {
assert(!bar.empty()); // ss was copied!
}
};
int main() {
std::string baz("F00B4R");
Foo foo(baz);
assert(!baz.empty()); // baz is no more necessary!
return 0;
}
http://ideone.com/fzZHCB
28. RVALUE REFERENCES AND MOVE SEMANTICS
#include <utility> // Temporary Object
class Foo {
std::string bar;
public:
Foo(std::string&& ss) : bar(std::move(ss)) {
assert(!bar.empty()); // ss was moved!
}
};
int main() {
std::string baz("F00B4R");
Foo foo(std::move(baz));
assert(baz.empty()); // baz was moved!
return 0;
}
http://ideone.com/fzZHCB
29. RVALUE REFERENCES AND MOVE SEMANTICS
•About move and forward functions
•move doesn’t move;
•forward doesn’t forward;
•neither does anything at runtime;
•generate nothing.
30. RVALUE REFERENCES AND MOVE SEMANTICS
•About move and forward functions
•move and forward are functions that performs casts;
•move is a unconditional cast to an rvalue;
•forward performs this cast only if a particular condition is fulfilled.
template<typename T>
typename remove_reference<T>::type&&
move(T&& param)
{
using ReturnType = typename remove_reference<T>::type&&;
return static_cast<ReturnType>(param);
}
•move returns a && type (rvalue reference);
•remove_reference ensures that && is applied only to non-reference.
31. RVALUE REFERENCES AND MOVE SEMANTICS
•Perfect Forward
•write function templates that take arbitrary arguments;
•forward exactly the same arguments as were passed.
•Consider:
template <class T>
std::shared_ptr<T>
factory()
{
return std::make_shared<T>();
}
32. RVALUE REFERENCES AND MOVE SEMANTICS
template <class T, class Arg>
std::shared_ptr<T>
factory(Arg& arg)
{
return std::make_shared<T>(arg);
}
int main() {
std::string ss("FOO");
auto foo = factory<std::string>(ss);
auto bar = factory<std::string>(std::move(ss)); // error!
return 0;
}
33. RVALUE REFERENCES AND MOVE SEMANTICS
template <class T, class Args>
std::shared_ptr<T>
factory(Args&& args)
{
return std::make_shared<T>(std::forward<Args>(args));
}
•forward preserves the lvalue/rvalue-ness of the argument that
was passed to factory;
•Args&& can be anything.
34. RVALUE REFERENCES AND MOVE SEMANTICS
•Things to remember
•move can be cheaper than copy;
•std::move doesn’t move; it’s an unconditional cast to an rvalue;
•std::forward doesn’t forward; it’s casts its argument to an rvalue only if
that argument is bound to an rvalue;
35. RVALUE REFERENCES AND MOVE SEMANTICS
•Universal References
•sometimes && is not a rvalue reference.
class Foo{};
// ...
Foo&& foo = Foo(); // && means rvalue reference
auto&& bar = foo; // && doesn't mean rvalue reference
template<typename T>
void process(std::vector<T>&& args); // && means rvalue reference
template<typename T>
void process(T&& args); // && doesn't mean rvalue reference
36. RVALUE REFERENCES AND MOVE SEMANTICS
•Universal References
•can binds rvalue reference;
•can binds lvalue reference;
•can binds const or non-consts objects.
class Foo{};
// ...
Foo&& foo = Foo(); // we can obtain the address of foo
auto&& bar = foo; // so, bar is a reference to a lvalue
Foo& bar = foo; // same
37. RVALUE REFERENCES AND MOVE SEMANTICS
•Universal References
template<typename T>
void process(T&& args) {}
process(10); // 10 is a rvalue; T&& is a rvalue reference
Foo foo;
process(foo); // foo is a lvalue; T&& is a lvalue reference, as Foo&
template <typename T>
void foobar(const T&& param) {} // const qualifier disables uref
38. RVALUE REFERENCES AND MOVE SEMANTICS
•Universal References
•use move on rvalue references and forward on universal references;
class Foo {
std::string bar;
public:
template <typename T>
void set_bar(T&& t) { bar = std::move(t); }
};
int main() {
std::string baz{"F00B4R"};
Foo foo;
foo.set_bar(baz);
assert(!baz.empty()); // Ops!
return 0;
}
http://ideone.com/MXdPXx
39. RVALUE REFERENCES AND MOVE SEMANTICS
•Universal References
•use move on rvalue references and forward on universal references;
class Foo {
std::string bar;
public:
void set_bar(std::string&& ss) { bar = std::move(ss); }
};
int main() {
std::string baz{"F00B4R"};
Foo foo;
foo.set_bar(baz); // error: no mathing function
assert(!baz.empty());
return 0;
}
http://ideone.com/WFlcon
40. RVALUE REFERENCES AND MOVE SEMANTICS
•Things to remember: Universal References
•auto&& and T&& for a deduces type T, are universal reference;
•universal references are lvalue references when initialized with
lvalues;
•universal references are rvalue references when initialized with
rvalues;
•use move on rvalue references;
•use forward on universal references.
41. RVALUE REFERENCES AND MOVE SEMANTICS
•Consider pass by value when cheaper: Overloading
class Foo {
std::vector<std::string> foobar;
public:
void insert(const std::string& ss) {
foobar.push_back(ss); // Copy!
}
void insert(std::string&& ss) {
foobar.push_back(std::move(ss));
}
};
int main() {
Foo foo;
std::string bar("B4R");
foo.insert(bar); // insert by lvalue
foo.insert("F00"); // insert by rvalue
return 0;
} // http://ideone.com/Qb3ASJ
42. RVALUE REFERENCES AND MOVE SEMANTICS
•Consider pass by value when cheaper: Universal Reference
class Foo {
std::vector<std::string> foobar;
public:
template <typename T>
void insert(T&& ss) {
foobar.push_back(std::forward<T>(ss));
}
};
int main() {
Foo foo;
std::string bar("B4R");
foo.insert(bar); // insert by lvalue
foo.insert("F00"); // insert by rvalue
return 0;
}
http://ideone.com/EPmSho
43. RVALUE REFERENCES AND MOVE SEMANTICS
•Consider pass by value when cheaper: Passing by value
class Foo {
std::vector<std::string> foobar;
public:
void insert(std::string ss) {
foobar.push_back(std::move(ss));
}
};
int main() {
Foo foo;
std::string bar("B4R");
foo.insert(bar); // insert by lvalue
foo.insert("F00"); // insert by rvalue
return 0;
}
http://ideone.com/c1Hsv7
44. RVALUE REFERENCES AND MOVE SEMANTICS
•Overloading
•one copy for lvalues;
•one move for rvalues.
•Universal Reference
•one copy for lvalues;
•one move for rvalues.
•Passing by value
•one copy + one move for lvalues;
•two moves for rvalues;
+ parameters that are always copied;
+ nearly efficient as pass by reference;
+ easier to implement;
+ can generate less object code.
46. STATIC ASSERTIONS
#if sizeof(unsigned) >= 8
# error "64-bit arch is not supported"
#endif
int main() { return 0; }
#include <type_traits>
static_assert(sizeof(unsigned) >= 8, "64-bit arch is not
supported");
int main() { return 0; }
error: static assertion failed: 64-bit arch is not supported
// http://ideone.com/OmYixS
47. STATIC ASSERTIONS
#include <type_traits>
template <typename T>
void foobar() {
static_assert(std::is_copy_constructible<T>::value, "Type
T must be copyable");
}
struct Foo { Foo(const Foo&) = delete; };
int main() {
foobar<Foo>();
return 0;
}
error: static assertion failed: Type T must be copyable
// http://ideone.com/DxRSnI
48. STATIC ASSERTIONS
•Things to remember:
•the compiler evaluates the expression;
•it cannot be used to check assumptions that depends on run-
time values.
49. PREVENTING EXCEPTION PROPAGATION
// C++98 - no exceptions
void foo() throw()
{
}
•callers might be dependent on the original exception;
•if the exception specification is violated, then
the call stack is unwound to to foo’s caller.
50. PREVENTING EXCEPTION PROPAGATION
// C++11
void bar() noexcept
{
}
•the stack is only possibly unwound before
program execution is terminated;
•So, optimizers need not keep the runtime stack in an
unwindable state.
•it permits compilers to generate better object code!
51. PREVENTING EXCEPTION PROPAGATION
// C++11 - cannot throw an exception
void foo() noexcept { }
// as before
void bar() noexcept(true) { }
// permit exceptions to propagate
void qux() noexcept(false) { }
53. PREVENTING EXCEPTION PROPAGATION
•Things to remember:
•‘noexcept’ is simply a shorthand for noexcept(true);
•noexcept(false) specifies that it does permit exceptions to
propagate;
•Use noexcept instead of the exception specifier throw,
which is deprecated in C++11 and later;
• noexcept enables compilers to generate more efficient
code;
•noexcept is particularly valuable for the move operations,
swap, memory deallocation functions, and destructors;
•apply noexcept to a function when you are sure it will never
allow an exception to propagate up the call stack.
54. OVERRIDE CONTROLS
•Rules for override
•The base class function must be virtual;
•The base and derived function names must be identical
(except in the case of destructors);
•The parameter types of the base and derived functions must
be identical;
•The constness of the base and derived functions must be
identical;
•The return types and exception specifications of the base and
derived functions must be compatible.
•C++11 adds one more:
•The functions’ reference qualifiers must be identical.
58. SCOPED AND STRONGLY TYPED ENUMS
The enum classes ("new enums", "strong enums") address three
problems with traditional C++ enumerations:
Conventional enums implicitly convert to int, causing errors when
someone does not want an enumeration to act as an integer;
Conventional enums export their enumerators to the surrounding
scope, causing name clashes.
The underlying type of an enum cannot be specified, causing
confusion, compatibility problems, and makes forward declaration
impossible.
from: http://www.stroustrup.com/C++11FAQ.html#enum
59. SCOPED AND STRONGLY TYPED ENUMS
// C++98 - unscoped enums.
enum Status { OK, ERROR = 100, INVALID, UNKNOWN = 0xFFFF };
int status = ERROR;
enum Device { UNKNOWN, PRINTER, KEYBOARD };
// error: redeclaration of ‘UNKNOWN’
// C++11 - scoped enums.
enum class Status { OK, ERROR = 100, INVALID, UNKNOWN };
enum class Device { PRINTER, KEYBOARD, UNKNOWN = 0xFFFF };
auto status = UNKNOWN;
// error: ‘UNKNOWN’ was not declared in this scope
auto status = Status::UNKNOWN;
60. SCOPED AND STRONGLY TYPED ENUMS
// C++11 - Specify the underlying type
#include <iostream>
enum class Signal : char { YES = 'Y', NO = 'N' };
int main() {
char signal = Signal::YES;
std::cout << signal << std::endl;
return 0;
}
error: cannot convert ‘Signal’ to ‘char’ in initialization
auto signal = static_cast<char>(Signal::YES);
61. SCOPED AND STRONGLY TYPED ENUMS
// C++11 - Specify the underlying type
#include <iostream>
enum class Signal : char;
void foo(Signal signal) {
std::cout << static_cast<char>(signal) << std::endl;
}
enum class Signal : char { YES = 'Y', NO = 'N' };
int main() {
auto signal = Signal::YES;
foo(signal);
return 0;
}
63. LAMBDA EXPRESSION
•About lambda function
•inline anonymous functor;
•specify a simple action to be performed by some function;
•similiar to the idea of a functor or function pointer;
•can use std::function as wrapper.
•Syntax
[ capture-list ] ( params ) -> return-type { body }
65. LAMBDA EXPRESSION
using Bar = std::function<double(double, double)>;
int main() {
auto foo = []() { std::cout << "FOO" << std::endl; };
foo();
Bar bar = [] (double a, double b) -> double { return a * b; };
std::cout << bar(5, 2) << std::endl;
std::string ss{"F00B4R"};
[] () { std::cout << ss << std::endl; };
return 0;
}
http://ideone.com/2iU3rc
66. LAMBDA EXPRESSION
•Capture List
[ ] Capture nothing (or, a scorched earth strategy?)
[&] Capture any referenced variable by reference
[=] Capture any referenced variable by making a copy
[=, &foo] Capture any referenced variable by making a copy,
but capture variable foo by reference
[bar] Capture bar by making a copy; don't copy anything else
[this] Capture the this pointer of the enclosing class
67. LAMBDA EXPRESSION
// C++14
#include <cassert>
auto foo(auto bar) {
return bar * 2;
}
int main() {
auto baz = [](auto qux) { return qux * 2; };
assert(foo(1));
assert(baz(2));
return 0;
}
http://ideone.com/kjnUme
68. LAMBDA EXPRESSION
•Things to remember:
•avoid capture any referenced variable by reference (dangling ref);
•Lambdas are more readable, more expressive, and may be more
efficient than using std::bind.
69. DEFAULTED AND DELETED FUNCTIONS
struct Bar {};
struct Baz { Bar* bar; };
int main() {
Baz baz{new Bar{}};
Baz bazfoo = baz; // bazfoo copy from baz!
return 0;
}
•Prohibiting copying idiom:
•Use boost::noncopyable.
•Declare copy constructor as private
70. DEFAULTED AND DELETED FUNCTIONS
struct Bar {};
struct Baz {
Bar* bar;
Baz(const Baz&) = delete; // disallow copy constructor
};
int main() {
Baz baz{new Bar{}};
Baz bazfoo = baz; // error: use of deleted function
return 0;
}
71. DEFAULTED AND DELETED FUNCTIONS
struct BigNumber {
BigNumber(long long) {}
BigNumber(int) = delete;
};
int main()
{
BigNumber(5ll);
BigNumber(42); // deleted function
return 0;
}
72. DEFAULTED AND DELETED FUNCTIONS
•What are the special member functions of C++11?
•Default constructor C::C();
•Destructor C::~C();
•Copy constructor C::C (const C&);
•Copy assignment C& operator= (const C&);
•Move constructor C::C (C&&);
•Move assignment C& operator= (C&&);
73. DEFAULTED AND DELETED FUNCTIONS
Special Member Function Implicity defined Default definition
Default constructor if no other constructors does nothing
Destructor if no destructor does nothing
Copy Contructor if no move constructor and
no move assignment
copies all members
Copy Assignment if no move constructor and
no move assignment
copies all members
Move Constructor if no destructor, no copy
constructor and no copy nor
move assignment
moves all members
Move Assignment if no destructor, no copy
constructor and no copy nor
move assignment
moves all members
76. SMART POINTERS
•RAII (Resouce Acquisition Is Initialization)
•Programming technique which binds the life cycle of a resource to
the lifetime of an object with automatic storage duration;
•Scope-Bound Resource Management (SBRM);
•RAII - Summary
•encapsulate each resource into a class, where the constructor
acquires the resource and establishes all class invariants or throws
an exception if that cannot be done, the destructor releases the
resource and never throws exceptions;
•always use the resource via an instance of a RAII-class that either
has automatic storage duration, is a non-static member of a class
whose instance has automatic storage duration.
78. SMART POINTERS
#include <mutex>
void consummer() {
std::lock_guard<std::mutex> lock(mutex) // Safe! Using RAII
auto worker = work_queue.front();
work_queue.pop();
worker(); // throw exception. mutex will be unlocked
}
79. SMART POINTERS
•Look and feel like pointers, but are smarter
•an object that owns another object and manages that other object
through a pointer;
•support pointer operations like dereferencing (operator *) and
indirection (operator ->);
•Automatic cleanup;
•Automatic initialization;
•Exception safety;
86. SMART POINTERS - UNIQUE_PTR
#include <iostream>
#include <memory>
#include <functional>
struct Bar {
~Bar() { std::cout << 2; }
static void deleter(Bar*) { std::cout << 1; }
};
int main() {
using bar_delete = std::function<void(Bar*)>;
auto bar = std::unique_ptr<Bar, bar_delete>(
new Bar(), Bar::deleter);
return 0;
}
http://ideone.com/8VTUEe
87. SMART POINTERS - UNIQUE_PTR
•Things to remember:
•strict ownership;
•not copyable;
•moveable;
•deletes using an associated deleter;
•exception safety;
•can be stored in containers;
•return allocated pointer by function.
91. SMART POINTERS - SHARED_PTR
•Things to remember:
•shared ownership;
•copyable;
•moveable;
•deletes using an associated deleter;
•exception safety;
•can be stored in containers;
•return allocated pointer by function;
•there is control block;
•avoid create shared_ptr from variables of raw pointers.
92. SMART POINTERS - WEAK_PTR
struct Port;
struct Aggregation { std::list<std::shared_ptr<Port>> children; };
struct Port { std::shared_ptr<Aggregation> parent; };
int main() {
auto aggregation = std::make_shared<Aggregation>();
auto ports = { std::make_shared<Port>(), std::make_shared<Port>() };
aggregation->children = ports;
for (auto& port : aggregation->children) {
port->parent = aggregation;
}
return 0;
}
// http://ideone.com/YldGSH
93. SMART POINTERS - WEAK_PTR
struct Port;
struct Aggregation { std::list<std::shared_ptr<Port>> children; };
struct Port { std::weak_ptr<Aggregation> parent; };
int main() {
auto aggregation = std::make_shared<Aggregation>();
auto ports = { std::make_shared<Port>(), std::make_shared<Port>() };
aggregation->children = ports;
for (auto& port : aggregation->children) {
port->parent = aggregation;
}
return 0;
}
// http://ideone.com/fKq2hr
95. SMART POINTERS - WEAK_PTR
•Things to remember:
•wraps a weakly linked pointer;
•models temporary ownership;
•break 'circular references' with shared_ptr;
•would be a cache;
•solve the dangling pointer problem.
96. STANDARD CONTAINER ARRAY
“like a built-in array without the problems” - bjarne
// C++98
static const size_t BUFFER_SIZE = 20;
unsigned buffer [BUFFER_SIZE] = {};
// C++11
#include <array>
constexpr auto BUFFER_SIZE = 20;
std::array<unsigned, BUFFER_SIZE> buffer;
97. STANDARD CONTAINER ARRAY
// C++11
#include <array>
std::array<int, 5> foo;
auto foobar = foo[3]; // foobar is zero. Default elements are zero
auto* bar = foo;
// error: std::array doesn't implicitly convert to a pointer
auto* bar = foo.data(); // okay!
unsigned baz [] = { 1, 2, 4, 8, 16, 32 };
std::array<unsigned> qux = { 1, 2, 4, 8, 16, 32 };
// error: wrong number of template arguments
98. STANDARD CONTAINER ARRAY
template <class T> typename T::value_type sum(const T& t)
{
return std::accumulate(t.begin(), t.end(), 0);
}
int main() {
std::vector<unsigned> foo = { 1, 2, 4, 8 };
auto bar = sum(foo); // bar is 15
unsigned qux [] = { 1, 2, 4, 8 };
bar = sum(qux); // error: no matching function for call
std::array<unsigned, 4> baz = { 1, 2, 4, 8 };
bar = sum(baz); // bar is 15
return 0;
}
// http://ideone.com/IAksgE
104. CONSTANT EXPRESSIONS
•Use constexpr whenever possible
•Objects: const + value known during compilation.
•Functions: return constexpr result if called with constexpr args.
105. CONSTANT EXPRESSIONS
•constexpr objects
constexpr auto foo = 42; // Okay!
constexpr auto bar = foo; // Okay!
bar = 11; // error: assignment of read-only variable 'bar'
std::array<unsigned, foo> qux; // Okay!
static_assert(foo == 42, "Foo must be 42!"); // Okay!
int size = 42;
constexpr auto foobar = size; // error: the value of 'size' is not usable in
a constant expression
106. CONSTANT EXPRESSIONS
•constexpr objects vs const objects
int bar = 42;
const auto foo = bar; // okay: may be initialized at runtime
std::array<unsigned, foo> qux; // error: foo is not a constant expression
•All constexpr objects are const, but not all const objects are constexpr.
•If you need compile-time value, then constexpr is the proper tool.
107. CONSTANT EXPRESSIONS
•constexpr objects vs const objects
int bar = 42;
const auto foo = bar; // okay: may be initialized at runtime
std::array<unsigned, foo> qux; // error: foo is not a constant expression
•All constexpr objects are const, but not all const objects are constexpr.
•If you need compile-time value, then constexpr is the proper tool.
108. CONSTANT EXPRESSIONS
•constexpr objects rules:
•may any literal type including:
•float point types
•char literals
•pointer literals
•literal obejcts
•requires no storage declaration
•constexpr parameters not allowed:
void foo(constexpr int bar) // error: could not be constexpr
{
std::array<int, bar> qux;
}
109. CONSTANT EXPRESSIONS
•constexpr functions:
•execute during compile-time, and return constexpr, only:
•the arguments are constexpr
•the result is used in constexpr context
•execute (perphaps not) during compile-time, when:
•the arguments are constexpr
•the result is not used in constexpr context
•execute at run-time when there is 1 or more non-constexpr arguments.
•no need to overload,
•constexpr function take both constexpr and non-constexpr args.
110. CONSTANT EXPRESSIONS
constexpr int half_of(double value) noexcept { return value / 2; }
int main() {
constexpr auto foo = half_of(42); // compile-time call
static_assert(foo == 21, "Ops!");
auto bar = half_of(12); // runtime call
assert(bar == 6);
const auto foobar = half_of(12); // compile-time call
static_assert(foobar == 6, "Ops!");
auto qux = 74;
auto couse = half_of(qux); // runtime call
assert(couse == 37);
return 0;
}
111. CONSTANT EXPRESSIONS
•constexpr functions rules:
•its return type shall be a literal type; and
•its parameter types shall be literal types; and
•its function-body shall be a compound-statement of the form:
{ return expression; }
where expression is a potential constant expression; and
•every implicit conversion used in converting expression to the function
return type shall be one of those allowed in a constant expression.
•constexpr functions and constexpr constructors are implicitly inline
•a constexpr function shall not be virtual
112. CONSTANT EXPRESSIONS
•constexpr functions:
constexpr int square(int x) { return x * x; } // OK
constexpr long long_max() { return 2147483647; } // OK
constexpr int abs(int x) { return x < 0 ? -x : x; } // OK
constexpr void f(int x) { /* ... */ } // error: return type is void
constexpr int prev(int x) { return --x; } // error: use of decrement
constexpr int g(int x, int n) {
int r = 1; // error: body not just “return expr’’
while (--n > 0) r *= x;
return r;
}
113. CONSTANT EXPRESSIONS
•Relaxed constexpr restrictions C++14:
•any declaration, except:
•static
•thread_local
•conditional branching statements if and switch;
•any looping statement, including range-based for;
•change the value of an object if the lifetime of that object began within
the constant expression function;
constexpr int pow(int base, int exp) noexcept {
auto result = 1;
for (int i = 0; i < exp; ++i) result *= base;
return result;
}
114. CONSTANT EXPRESSIONS
•Things to remember:
•constexpr objects are const and are initialized with values known during
compilation.
•constexpr functions can produce compile-time results when called with
arguments whose values are known during compilation.
•constexpr objects and functions may be used in a wider range of
contexts than non-constexpr objects and functions.
•constexpr is part of an object’s or function’s interface.
115. THE ELEMENTS OF C++11
•How to improve my skills:
•books:
•more effective c++ and modern effective c++; Scott Meyers
•a tour of C++; bjarne stormtrooper
•web
•https://isocpp.org/
•http://scottmeyers.blogspot.com/
•http://herbsutter.com/
•http://erdani.com/
•http://cppcon.org/
•http://cppcast.com/