Support for Embedded Programming in C++11 and C++14



Similar documents
Object Oriented Software Design II

CORBA Programming with TAOX11. The C++11 CORBA Implementation

The Evolving Search for Effective C++

N3458: Simple Database Integration in C++11

C++ INTERVIEW QUESTIONS

Object Oriented Software Design

Unified Call Syntax: x.f(y) and f(x,y)

MSP430 C/C++ CODE GENERATION TOOLS Compiler Version 3.2.X Parser Error/Warning/Remark List

Variable Base Interface

vector vec double # in # cl in ude <s ude tdexcept> tdexcept> // std::ou std t_of ::ou _range t_of class class V Vector { ector {

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Functional Programming in C++11

Object Oriented Software Design

sqlpp11 - An SQL Library Worthy of Modern C++

Qt Signals and Slots. Olivier Goffart. October 2013

Konzepte objektorientierter Programmierung

Coding conventions and C++-style

Binary storage of graphs and related data

The programming language C. sws1 1

To Java SE 8, and Beyond (Plan B)

The D Programming Language

Applied Informatics C++ Coding Style Guide

A Standardized Representation of Asynchronous Operations

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Objectif. Participant. Prérequis. Remarque. Programme. C# 3.0 Programming in the.net Framework. 1. Introduction to the.

Computer Programming I

Generalizing Overloading for C++2000

C++ Programming Language

Chapter 7: Functional Programming Languages

C++ for Safety-Critical Systems. DI Günter Obiltschnig Applied Informatics Software Engineering GmbH

For the next three questions, consider the class declaration: Member function implementations put inline to save space.

CSE 373: Data Structure & Algorithms Lecture 25: Programming Languages. Nicki Dell Spring 2014

Chapter 5 Names, Bindings, Type Checking, and Scopes

Why you shouldn't use set (and what you should use instead) Matt Austern

C++ Support for Abstract Data Types

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

: provid.ir

Course Name: ADVANCE COURSE IN SOFTWARE DEVELOPMENT (Specialization:.Net Technologies)

El Dorado Union High School District Educational Services

C++ Overloading, Constructors, Assignment operator

Integrating the C++ Standard Template Library Into the Undergraduate Computer Science Curriculum

SFINAE Functionality Is Not Arcane

MPLAB Harmony System Service Libraries Help

OpenCL Static C++ Kernel Language Extension

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

Thomas Jefferson High School for Science and Technology Program of Studies Foundations of Computer Science. Unit of Study / Textbook Correlation

C Compiler Targeting the Java Virtual Machine

Java Interview Questions and Answers

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1

Object Oriented Software Design II

SystemVerilog Is Getting Even Better!

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Moving from CS 61A Scheme to CS 61B Java

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

History OOP languages Year Language 1967 Simula Smalltalk

Visual Basic. murach's TRAINING & REFERENCE

Getting Started with the Internet Communications Engine

16 Collection Classes

AP Computer Science Java Subset

C and C++: Case Studies in Compatibility


INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

Syntax Check of Embedded SQL in C++ with Proto

C++ Crash Kurs. C++ Object-Oriented Programming

Specialized Android APP Development Program with Java (SAADPJ) Duration 2 months

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Basic Programming and PC Skills: Basic Programming and PC Skills:

AppendixA1A1. Java Language Coding Guidelines. A1.1 Introduction

C++ Front End Internal Documentation (excerpt)

Programming and Software Development CTAG Alignments

Course MS10975A Introduction to Programming. Length: 5 Days

C#5.0 IN A NUTSHELL. Joseph O'REILLY. Albahari and Ben Albahari. Fifth Edition. Tokyo. Sebastopol. Beijing. Cambridge. Koln.

Comp 411 Principles of Programming Languages Lecture 34 Semantics of OO Languages. Corky Cartwright Swarat Chaudhuri November 30, 20111

6.088 Intro to C/C++ Day 4: Object-oriented programming in C++ Eunsuk Kang and Jean Yang

Crash Course in Java

Fundamentals of Java Programming

Course Title: Software Development

#820 Computer Programming 1A

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Informatica e Sistemi in Tempo Reale

VB.NET INTERVIEW QUESTIONS

Compiler Construction

C++ Language Tutorial

Programming in C# with Microsoft Visual Studio 2010

C++FA 3.1 OPTIMIZING C++

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

Chapter 1 Fundamentals of Java Programming

POLYTYPIC PROGRAMMING OR: Programming Language Theory is Helpful

JOINT STRIKE FIGHTER. December 2005

Java 7 Recipes. Freddy Guime. vk» (,\['«** g!p#« Carl Dea. Josh Juneau. John O'Conner

SQL Server for developers. murach's TRAINING & REFERENCE. Bryan Syverson. Mike Murach & Associates, Inc. Joel Murach

TypeScript. Language Specification. Version 1.4

Class 16: Function Parameters and Polymorphism

Programming in C# with Microsoft Visual Studio 2010

Glossary of Object Oriented Terms

Transcription:

Support for Embedded Programming in C++11 and C++14 Scott Meyers, Ph.D. Photo: Craig Wyzlk @ flickr Copyrighted material, all rights reserved. Last Revised: 10/24/14 Features New in C++11 (Incomplete List) auto explicit conversion functions alias templates range-based for override, final move semantics scoped enums underlying type for enums static_assert smart pointers make_shared, allocate_shared variadic templates lambda expressions enhanced const_iterator support std::bind type traits numeric string conversions tuples alignment control >> as nested template closer regular expressions user-defined literals default member initializers singly-linked lists hash tables support for emplacement new algorithms perfect forwarding support for concurrency enable_if constexpr support for Unicode rvalue references raw string literals uniform (braced) initialization universal references std::array inherited & delegated constructors nullptr initializer_list std::function defaulted functions decltype trailing return types deleted functions Slide 2

Features New in C++14 (Incomplete List) Generalized function return type deduction Generic lambdas Lambda init capture Relaxed rules for constexpr functions Binary literals Single quote as digit separator Variable templates Global operator delete with size parameter [[deprecated]] attribute make_unique Non-member cbegin, cend, rbegin, rend, crbegin, crend Literal suffixes for string, <chrono> units, complex numbers Readers-Writer locks IO support for quoted strings Type-based tuple access Aliases for transformation traits Simplified operator functor templates Slide 3 C++11 and C++14 Features Most as useful for embedded as for non-embedded development. Covering even mentioning everything not possible. Slide 4

Agenda auto Enhanced enums (if time allows) Alignment control (in Bartek Szurgot s talk) constexpr Slide 5 auto Slide 6

Prefer auto to Explicit Type Declarations Given Widget w = expression of type Widget; auto w = expression of type Widget; why prefer auto? Slide 7 Prefer auto to Explicit Type Declarations Mandatory initialization: int sum; // possibly uninitialized auto sum; // error! no initializer from which // to deduce type auto sum = 0; // fine, sum is int initialized to 0 Slide 8

Prefer auto to Explicit Type Declarations Typically less verbose; avoids syntactic noise: std::vector<std::string::iterator> vsi; for (std::string::iterator si : vsi) // explicit type for (auto si : vsi) // auto template<typename It> void somealgorithm(it b, It e) { typename std::iterator_traits<it>::value_type // explicit firstelem = *b; // type auto firstelem = *b; // auto } Slide 9 Prefer auto to Explicit Type Declarations Avoids type shortcut -related problems. std::vector<int> v; unsigned sz = v.size(); // type shortcut! // (should be // std::vector<int>::size_type) Fine on 32-bit Windows. unsigned and std::vector<int>::size_type are 32 bits. Unreliable on 64-bit Windows. unsigned is 32 bits, std::vector<int>::size_type is 64 bits. auto sz = v.size(); // sz is std::vector<int>::size_type Example due to Andrey Karpov. Slide 10

Prefer auto to Explicit Type Declarations Avoids accidental temporary creation: std::map<std::string, int> m; // holds objects of type // std::pair<const std::string, // int> for (const std::pair<std::string, int>& p : m) // creates temp on // each iteration // std::string is copied for (const auto& p : m) // no temps created Example due to Stephan T. Lavavej. Slide 11 Prefer auto to Explicit Type Declarations Most efficient way to store function objects: std::function<int(int)> f1a = [a,b](int x) { return x*x - a/10 + b; }; // closure could // be on heap auto f1b = [a,b](int x) { return x*x - a/10 + b; }; // closure not on // heap Slide 12

Prefer auto to Explicit Type Declarations Efficiency difference not limited to closures: inline void f(int x, int y, int z) { } std::function<void()> f2a = // func. obj. from std::bind std::bind(f, a, b, c); // could be on heap auto f2b = std::bind(f, a, b, c); // func. obj. from std::bind // not on heap Slide 13 auto a tool, not an obligation. auto and Code Clarity If explicit type clearer, use it. But: IDEs may show types of auto-declared variables. E.g. Visual Studio 2010+. Much success in other languages with similar features. Slide 14

auto Slide 15 constexpr Slide 16

Two meanings: Use constexpr Whenever Possible Objects: const + value known during compilation. Functions: return constexpr result if called with constexpr args. Truth a bit more subtle. Slide 17 constexpr Objects Must be initialized with value known during compilation: constexpr std::size_t arraysize; int sz; constexpr auto arraysize1 = sz; constexpr auto arraysize2 = 10; // error! no initializer // non-constexpr variable // error! sz's value not // known at compilation // okay Usable in contexts requiring compile-time constants: std::array<int, sz> data1; std::array<int, arraysize2> data2; const (hence unmodifiable): arraysize2 = 100; // error! sz's value still // unknown at compilation // fine, arraysize2 // is constexpr // error! Slide 18

constexpr Objects vs. const Objects const objects may be initialized at runtime: int sz; const auto arraysize3 = sz; // as before // fine, arraysize3 is // const copy of sz Such objects invalid in contexts requiring compile-time values: std::array<int, arraysize3> data3; // error! arraysize3 // isn't constexpr All constexpr objects are const, but not all const objects are constexpr. Slide 19 Bottom line: constexpr Objects vs. const Objects Need compile-time value constexpr is proper tool. When constexpr viable, use it. Resulting object usable in more contexts. const int maxval = 100; constexpr int maxval = 100; // typically inferior // typically superior Slide 20

constexpr Functions Quite different from const functions. Not limited to member functions. Execute during compilation and return constexpr results if : Arguments are constexpr. Result used in constexpr context. May (but may not) execute during compilation if: Arguments are constexpr. Result not used in constexpr context. Execute at runtime for 1 non-constexpr argument. No need to overload on constexpr. constexpr functions take constexpr and non-constexpr args. Note: constexpr functions may not return const results. constexpr functions may not execute during compilation. Slide 21 Consider an experiment where: constexpr Functions 3 possible lighting levels: high, low, off. 3 possible fan speeds: high, low, off. 3 possible temperature values: high, medium, low. Etc. n independent 3-valued conditions 3 n combinations. Holding all results in a std::array compute 3 n during compilation. Goal: calculate with constexpr function. Slide 22

Client view: constexpr Functions constexpr int pow(int base, int exp) noexcept // constexpr { // function... // coming soon } constexpr auto numconds = 5; std::array<int, pow(3, numconds)> results; // fine, results // has 3^numConds // elements Note: pow called with constexpr values in a constexpr context. Guarantees compile-time evaluation. Slide 23 constexpr Functions pow also callable at runtime: auto base = readfromdb("base"); auto exp = readfromdb("exponent"); auto basetoexp = pow(base, exp); // runtime call // runtime call // runtime call Slide 24

constexpr Functions constexpr functions are constrained. May take and return only literal types. Essentially types where values compile-time-computable. Implementations restricted. Restrictions differ for C++11 and C++14. In C++11, exactly one executable statement: return. But?: emulates if/else and recursion emulates iteration, so: constexpr int pow(int base, int exp) noexcept { return (exp == 0? 1 : base * pow(base, exp - 1)); } Slide 25 C++14 restrictions much looser. constexpr Functions Multiple statements okay Local variables of literal type okay. Iteration statements okay. Etc. Hence: constexpr int pow(int base, int exp) noexcept // C++14 { // only auto result = 1; for (int i = 0; i < exp; ++i) result *= base; return result; } Slide 26

Literal types can be user-defined! Literal UDTs constexpr constructors and other member functions. class Point { public: constexpr Point(double xval = 0, double yval = 0) noexcept : x(xval), y(yval) {} constexpr double xvalue() const noexcept { return x; } constexpr double yvalue() const noexcept { return y; } void setx(double newx) noexcept { x = newx; } void sety(double newy) noexcept { y = newy; } private: double x, y; }; constexpr Point p1(9.4, 27.7); // fine constexpr Point p2(28.8, 5.3); // also fine Slide 27 Given Literal UDTs constexpr Point midpoint(const Point& p1, const Point& p2) noexcept { return { (p1.xvalue() + p2.xvalue()) / 2, // call constexpr (p1.yvalue() + p2.yvalue()) / 2 }; // member funcs } a constexpr Point object could be defined as follows: constexpr auto mid = midpoint(p1, p2); // init constexpr // object w/result of // constexpr function Slide 28

Literal UDTs In C++14, even setters can be constexpr: class Point { public:... constexpr void setx(double newx) noexcept { x = newx; } constexpr void sety(double newy) noexcept { y = newy; }... }; // C++14 only // C++14 only Slide 29 Hence: Literal UDTs // return reflection of p with respect to the origin constexpr Point reflection(const Point& p) noexcept { Point result; // create non-const Point result.setx(-p.xvalue()); // set its x and y values result.sety(-p.yvalue()); return result; // return constexpr copy of it } constexpr Point p1(9.4, 27.7); // as before constexpr Point p2(28.8, 5.3); constexpr auto mid = midpoint(p1, p2); // as before constexpr auto reflectedmid = reflection(mid); // reflectedmid's value // is (-19.1-16.5) and // a compile-time // constant Slide 30

Pros: constexpr Pros and Cons Can shift runtime work to compile time. May help move objects from RAM to ROM. constexpr begets constexpr. constexpr objects/functions facilitate creation of more constexpr objects/functions. Con: constexpr is interface. Removing constexpr can break arbitrary amounts of code. Use constexpr only if you re willing to commit to it. Slide 31 constexpr Slide 32

Enhanced enums Slide 33 Prefer Scoped enums to Unscoped enums Unscoped ( old ) enums have several weaknesses: enum Color { red, green, blue }; Namespace pollution: red, green, blue in scope containing enum. enum Color { red, green, blue }; void blue(); // error! Unspecified size: sizeof(color) up to implementation. Declaration-only not allowed: definition must be given. enum Options; // error! Slide 34

Prefer Scoped enums to Unscoped enums Weak typing: enumerators implicitly convert to int. enum Color { red, green, blue }; Color c; double d = c; // Color int double if (c) // Color int bool enum Options { debug, optimize, log }; Options opt; if (c == opt) // compare Color and Options! Slide 35 Scoped enums Scoped enums ( enum classes ) address all these issues: enum class Color; enum class Color { red, green, blue }; void blue(); Color c; double d = c; if (c) enum class Options { debug, optimize, log }; Options opt; if (c == opt) // fine // fine // error! // error! // error! Slide 36

Underlying Type Default underlying type for scoped enums is int: enum class Color { red, green, blue }; Can be overridden: // in binary code, // red, green, blue // are ints enum class Color: std::uint64_t // in binary code, { red, green, blue }; // red, green, blue // are std::uint64_ts Slide 37 Underlying Type Can now be specified for unscoped enums, too: enum Options: std::uint8_t { debug, optimize, log }; Such enums may also be forward-declared: enum Options: std::uint8_t; void dowork(std::function<void()> f, Options opts); But other issues remain: Namespace pollution Weak typing // forward declaration // fine Slide 38

enums, std::tuple, and std::get Use of scoped enums with std::get verbose: using StackOverflowData = std::tuple<std::string, // name std::size_t, std::size_t, std::size_t, // badges std::size_t>; // reputation enum class SOIndices { name, bronzecount, silvercount, goldcount, rep }; void processsouser(const StackOverflowData& user) { auto badgecount = std::get<std::size_t(soindices::bronzecount)>(user) + std::get<std::size_t(soindices::silvercount)>(user) + std::get<std::size_t(soindices::goldcount)>(user); } Even worse with static_casts Slide 39 enums, std::tuple, and std::get Enum int conversion makes use of unscoped enums simpler: enum { // not name, bronzecount, silvercount, goldcount, rep // enum }; // class void processsouser(const StackOverflowData& user) { auto badgecount = std::get<bronzecount>(user) + std::get<silvercount>(user) + std::get<goldcount>(user); } Slide 40

Casting to Underlying Type Verbosity of scoped enum approach can be reduced a bit: // cast enumerator to underlying type template<typename E> constexpr typename std::underlying_type<e>::type toutype(e enumerator) { return static_cast<typename std::underlying_type<e>::type>(enumerator); } void processsouser(const StackOverflowData& user) { auto badgecount = std::get<toutype(soindices::bronzecount)>(user) + std::get<toutype(soindices::silvercount)>(user) + std::get<toutype(soindices::goldcount)>(user); } toutype also more general than having clients cast to std::size_t: Not all enum-integral conversions call for std::size_ts. 2013 Scott Meyers, all rights reserved. Slide 41 Casting to Underlying Type Alias template can hide template blah_blah_blah::type syntax: template<typename E> // from previous slide constexpr typename std::underlying_type<e>::type toutype(e enumerator) { return static_cast<typename std::underlying_type<e>::type>(enumerator); } template<typename E> using UnderlyingType = typename std::underlying_type<e>::type; // alias // template template<typename E> // revised constexpr UnderlyingType<E> toutype(e enumerator) // toutype { return static_cast<underlyingtype<e>>(enumerator); } 2013 Scott Meyers, all rights reserved. Slide 42

Casting to Underlying Type C++14 s auto return type eliminates type repetition. Without alias template: template<typename E> constexpr auto toutype(e enumerator) // C++14 { return static_cast<typename std::underlying_type<e>::type>(enumerator); } With alias template: template<typename E> using UnderlyingType = typename std::underlying_type<e>::type; template<typename E> constexpr auto toutype(e enumerator) { return static_cast<underlyingtype<e>>(enumerator); } // C++14 Slide 43 Enhanced enums Slide 44

Further Information Slide 45 Further Information C++11 and C++14 in embedded systems: Embedded Programming with C++11, Rainer Grimm, Meeting C++, November 2013. Overviews prevention of narrowing conversions, static_assert, user-defined literals, constexpr, generalized PODs, std::array, move semantics, perfect forwarding, and smart pointers. C++14 Adds Embedded Features, William Wong, electronic design, 19 August 2014. Brief coverage of auto for lambda parameters and function return types, in-class aggregate initialization, user-defined literals, standard unit suffixes, constexpr, binary literals, and the digit separator. Slide 46

Effective use of C++11 and C++14: Effective Modern C++, Scott Meyers, O Reilly, 2015. Due out any day now... Further Information Slide 47 C++11: Further Information Programming Languages C++, Document 14882:2011, ISO/IEC, 2011-09-01. ISO product page: http://tinyurl.com/5soe87 (CHF238 ~$245). ANSI product page: http://tinyurl.com/8m6vb5m ($30). First post-standard draft (N3337): http://tinyurl.com/6wkboer (free). Essentially identical to the standard. C++11, Wikipedia. Overview of the New C++ (C++11/14), Scott Meyers, http://www.artima.com/shop/overview_of_the_new_cpp. Annotated training materials (analogous to these). The C++ Standard Library, Second Edition, Nicolai M. Josuttis, Addison-Wesley, 2012. Slide 48

C++14: Further Information Working Draft, Standard for Programming Language C++, Document N3797, ISO/IEC, 2013-10-13. Final freely available draft version of C++14. C++14, Wikipedia. The view from C++ Standard meeting April 2013, Michael Wong, C/C++ Cafe (blog) : Part 1, 25 April 2013. Discusses core language. Part 2, 26 April 2013. Discusses standard library. Part 3, 29 April 2013. Discusses concurrency and TSes. Overview of the New C++ (C++11/14), Scott Meyers, http://www.artima.com/shop/overview_of_the_new_cpp. Annotated training materials (analogous to these). Slide 49 auto: Further Information C++11, VC++11, and Beyond, Herb Sutter, Going Native 2012, 3 February 2012. Summarizes pros and cons of using auto. In what way can C++0x standard help you eliminate 64-bit errors, Andrey Karpov, viva64.com, 28 February 2010. Source of type shortcut example. STL11: Magic && Secrets, Stephan T. Lavavej, Going Native 2012, 2 February 2012. Source of accidental temporary example. Inferring too much, Motti Lanzkron, I will not buy this blog, it is scratched!, 21 February 2011. Slide 50

constexpr: Further Information Constexpr Generalized Constant Expressions in C++11, Alex Allain, cprogramming.com. Using constexpr to Improve Security, Performance, and Encapsulation in C++, Danny Kalev, Software Quality Matters Blog, 19 December 2012. constexpr, Jarryd Beck, The New C++ (blog), 14 November 2011. Slide 51 Enhanced enums: Further Information Strongly typed enumerations, Wikipedia, http://tinyurl.com/7szjdey. Subsection of entry for C++11. enum class -- scoped and strongly typed enums, Bjarne Stroustrup, http://tinyurl.com/2cvylcc. Subsection of C++11 the recently approved new ISO C++ standard. Closer to Perfection: Get to Know C++11 Scoped and Based Enum Types, Danny Kalev, smartbear.com, 6 February 2013. Better types in C++11 - nullptr, enum classes (strongly typed enumerations) and cstdint, Alex Allain, CPrograming.com. http://www.aristeia.com/ 2014 Scott Meyers, all rights reserved. Slide 52

Alias templates: Further Information Handling dependent names, R. Martinho Fernandes, Flaming Dangerzone, 27 May 2012. Slide 53 Licensing Information Scott Meyers licenses materials for this and other training courses for commercial or personal use. Details: Commercial use: Licensing/licensing.html Personal use: Licensing/personalUse.html Courses currently available for personal use include: Slide 54

About Scott Meyers Scott offers training and consulting services on the design and implementation of C++ software systems. His web site, provides information on: Training and consulting services Books, articles, other publications Upcoming presentations Professional activities blog Slide 55