This talk will present the current state of my work on designing and implementing Physical Units Library for C++. I will present all the challenges, design tradeoffs, and potential solutions to those problems. During the lecture, we will also see how new C++20 features help to make the library interface easier to use, maintain, and extend. Among others, we will see how we can benefit from class types provided as non-type template parameters, how new class template argument deduction rules simplify the interfaces and the full power of using concepts to constrain template types.
Implementing Physical Units Library for C++Mateusz Pusz
The document discusses implementing a library for physical units in C++. It begins with an example of the Mars Climate Orbiter mission failure caused by a discrepancy between units used by different software systems. It then reviews existing solutions like Boost.Units and discusses reasons for writing unit-aware code. The goal is to build a library that provides compile-time safety for units, supports multiple units and prefixes, and has no runtime overhead.
A Physical Units Library for the Next C++Mateusz Pusz
These are the slides from my CppCon 2020 talk. You can find the recording here: https://www.youtube.com/watch?v=7dExYGSOJzo. All my other talks can be found here: https://train-it.eu/resources.
---
During CppCon 2019 Mateusz provided an overview of current solutions on the market as well as challenges of implementing a modern C++ physical units library. This year's talk will focus on 'mp-units', the library that was developed by Mateusz and contributors, and which is proposed for C++ standardization. During the tutorial, we will get familiar with the building blocks of the library's framework and its most important concepts. Numerous code examples will present how to use and solve real-life problems with the library. The audience will learn how easy it is to extend it with new units, dimensions, or even whole new systems of quantities. Last but not least Mateusz will provide a fair comparison of how well this library performs in comparison to other products on the market.
Blasting Through the Clouds - Automating Cloud Foundry with Concourse CIFabian Keller
Cloud Foundry has an extremly high release velocity with new versions being available multiple times every week for a usual deployment. It is important for operators to deploy these releases in a timely manner in order to keep up with security patches and feature improvements. Commonly, there is not only one Cloud Foundry deployment to be kept up to date, but rather a couple of different stages that need to be upgraded in a specific order, for example from a sandbox to a development to a production environment.
Automation is key to keep up to date with Cloud Foundry's release velocity and Concourse CI is the continuous thing-doer of choice to do this honorable task. In this talk we'll first get to know Concourse CI basics and then see how we can leverage Concourse to automate staged platform updates for Pivotal Cloud Foundry. With pcf-automation being sunsetted in favor of PCF Automation we'll have a look at how we can tailor upgrade pipelines to suit different needs all while keeping the thrust at high pace to blast through the clouds!
Talk given at the Cloud Foundry Meetup Stuttgart in May 2019.
Object-Oriented Programming in Modern C++. Borislav Stanimirov. CoreHard Spri...corehard_by
Object-oriented programming has been criticized a lot. Every now and then some article or talk appears denouncing it and proclaiming that it's dead. This talk will do the opposite. It defends OOP and presents many modern libraries and concepts to show that it's very much alive and kicking.
어떻게 하면 배포 프로세스를 빠르게 개선할 수 있을까요?
git branch를 푸시하고 개별 테스트 서버를 만드려면 어떻게 해야 할까요?
쿠버네티스와 GitOps, Argo CD를 이용한 배포 방법을 소개 합니다.
Open Infrastructure & Cloud Native Days Korea 2019 발표자료
원본 슬라이드 다운로드 - http://bit.ly/subicura-gitops
Andrii Soldatenko "The art of data engineering"Fwdays
As the data space has increased, data engineering has emerged as a separate and related role that works together with data scientists. Usually, data scientists focus on finding new insights from a data set, while data engineers are concerned with the production readiness of that data.
In this talk, I’ll show you how to gather and collect the huge amount of data, store it, do batch processing or real-time processing on it, and how to build a data pipeline using Airflow for processing billions of records per table.
Also, we will discuss what is big data, and why it’s important to be able to process it so quick.
Git, CMake, Conan - How to ship and reuse our C++ projects?Mateusz Pusz
These are the slides from my CppCon 2018 talk. You can find the recording here: https://www.youtube.com/watch?v=S4QSKLXdTtA. All my other talks can be found here: https://train-it.eu/resources.
---
Git and CMake are already established standards in our community. However, it is uncommon to see them being used in an efficient way. As a result, many C++ projects have big problems with either importing other dependencies or making themselves easy to import by others. It gets even worse when we need to build many different configurations of our package on one machine.
That presentation lists and addresses the problems of build system and packaging that we have with large, multi-platform, C++ projects that often have many external and internal dependencies. The talk will present how proper use of CMake and Conan package manager can address those use cases. It will also describe current issues with the cooperation of those tools.
If you've attended or seen my talk at C++Now 2018, that time you can expect much more information on Conan and package creation using that tool. I will also describe how the integration of CMake and Conan changed over the last few months.
A Toolchain for Lean Architecture at American AirlinesShahir Daya
The document summarizes a presentation about American Airlines' transformation to a lean architecture and Agile development approach using IBM Cloud. Some key points:
- American Airlines wanted to adopt Agile but faced challenges with their monolithic website, complex applications, difficulty with regression tests, and siloed teams.
- The project aimed to transform AA.com, mobile apps, and kiosks to a modern microservices architecture on IBM Cloud to enable continuous innovation.
- They used an IBM Cloud Garage methodology with squads, guilds, and decentralized governance. Architecture was documented in tools developers used like GitHub.
- Lessons included evolving architecture incrementally, starting platform teams ahead of squads, and
Implementing Physical Units Library for C++Mateusz Pusz
The document discusses implementing a library for physical units in C++. It begins with an example of the Mars Climate Orbiter mission failure caused by a discrepancy between units used by different software systems. It then reviews existing solutions like Boost.Units and discusses reasons for writing unit-aware code. The goal is to build a library that provides compile-time safety for units, supports multiple units and prefixes, and has no runtime overhead.
A Physical Units Library for the Next C++Mateusz Pusz
These are the slides from my CppCon 2020 talk. You can find the recording here: https://www.youtube.com/watch?v=7dExYGSOJzo. All my other talks can be found here: https://train-it.eu/resources.
---
During CppCon 2019 Mateusz provided an overview of current solutions on the market as well as challenges of implementing a modern C++ physical units library. This year's talk will focus on 'mp-units', the library that was developed by Mateusz and contributors, and which is proposed for C++ standardization. During the tutorial, we will get familiar with the building blocks of the library's framework and its most important concepts. Numerous code examples will present how to use and solve real-life problems with the library. The audience will learn how easy it is to extend it with new units, dimensions, or even whole new systems of quantities. Last but not least Mateusz will provide a fair comparison of how well this library performs in comparison to other products on the market.
Blasting Through the Clouds - Automating Cloud Foundry with Concourse CIFabian Keller
Cloud Foundry has an extremly high release velocity with new versions being available multiple times every week for a usual deployment. It is important for operators to deploy these releases in a timely manner in order to keep up with security patches and feature improvements. Commonly, there is not only one Cloud Foundry deployment to be kept up to date, but rather a couple of different stages that need to be upgraded in a specific order, for example from a sandbox to a development to a production environment.
Automation is key to keep up to date with Cloud Foundry's release velocity and Concourse CI is the continuous thing-doer of choice to do this honorable task. In this talk we'll first get to know Concourse CI basics and then see how we can leverage Concourse to automate staged platform updates for Pivotal Cloud Foundry. With pcf-automation being sunsetted in favor of PCF Automation we'll have a look at how we can tailor upgrade pipelines to suit different needs all while keeping the thrust at high pace to blast through the clouds!
Talk given at the Cloud Foundry Meetup Stuttgart in May 2019.
Object-Oriented Programming in Modern C++. Borislav Stanimirov. CoreHard Spri...corehard_by
Object-oriented programming has been criticized a lot. Every now and then some article or talk appears denouncing it and proclaiming that it's dead. This talk will do the opposite. It defends OOP and presents many modern libraries and concepts to show that it's very much alive and kicking.
어떻게 하면 배포 프로세스를 빠르게 개선할 수 있을까요?
git branch를 푸시하고 개별 테스트 서버를 만드려면 어떻게 해야 할까요?
쿠버네티스와 GitOps, Argo CD를 이용한 배포 방법을 소개 합니다.
Open Infrastructure & Cloud Native Days Korea 2019 발표자료
원본 슬라이드 다운로드 - http://bit.ly/subicura-gitops
Andrii Soldatenko "The art of data engineering"Fwdays
As the data space has increased, data engineering has emerged as a separate and related role that works together with data scientists. Usually, data scientists focus on finding new insights from a data set, while data engineers are concerned with the production readiness of that data.
In this talk, I’ll show you how to gather and collect the huge amount of data, store it, do batch processing or real-time processing on it, and how to build a data pipeline using Airflow for processing billions of records per table.
Also, we will discuss what is big data, and why it’s important to be able to process it so quick.
Git, CMake, Conan - How to ship and reuse our C++ projects?Mateusz Pusz
These are the slides from my CppCon 2018 talk. You can find the recording here: https://www.youtube.com/watch?v=S4QSKLXdTtA. All my other talks can be found here: https://train-it.eu/resources.
---
Git and CMake are already established standards in our community. However, it is uncommon to see them being used in an efficient way. As a result, many C++ projects have big problems with either importing other dependencies or making themselves easy to import by others. It gets even worse when we need to build many different configurations of our package on one machine.
That presentation lists and addresses the problems of build system and packaging that we have with large, multi-platform, C++ projects that often have many external and internal dependencies. The talk will present how proper use of CMake and Conan package manager can address those use cases. It will also describe current issues with the cooperation of those tools.
If you've attended or seen my talk at C++Now 2018, that time you can expect much more information on Conan and package creation using that tool. I will also describe how the integration of CMake and Conan changed over the last few months.
A Toolchain for Lean Architecture at American AirlinesShahir Daya
The document summarizes a presentation about American Airlines' transformation to a lean architecture and Agile development approach using IBM Cloud. Some key points:
- American Airlines wanted to adopt Agile but faced challenges with their monolithic website, complex applications, difficulty with regression tests, and siloed teams.
- The project aimed to transform AA.com, mobile apps, and kiosks to a modern microservices architecture on IBM Cloud to enable continuous innovation.
- They used an IBM Cloud Garage methodology with squads, guilds, and decentralized governance. Architecture was documented in tools developers used like GitHub.
- Lessons included evolving architecture incrementally, starting platform teams ahead of squads, and
Streaming Topic Model Training and Inference with Apache FlinkDataWorks Summit
Analyzing streams of text data to extract topics is an important task for getting useful insights to be leveraged in subsequent workflows. For example, extracting topics from text to be continuously ingested into a search engine can be useful to tag documents with important
keywords or concepts to be used at search time. Another use case is doing analysis of support tickets to get insights on the most common problems for customers.
In this talk we illustrate how to use Apache Flink's Dynamic processing and Stateful streaming capabilities to continuously train topic models from unlabelled text and use such models to extract topics from the data itself. Such topic models will be built leveraging distributed representations of words and documents. We’ll be seeing as to how this can be all done in a pure streaming fashion without having to resort to a Lambda Architecture kind’a setup. An earlier version of this talk was presented at Flink Forward Berlin 2018.
The document provides an introduction to C++ programming, including:
- Getting started instructions for using the terminals in room B27 or the SCC to run C++ code.
- An overview of Code::Blocks, the integrated development environment that will be used for writing and compiling C++ programs.
- A first "Hello, World!" C++ program that introduces basic C++ syntax like main(), cout, headers, and comments.
- Demonstrations of C++'s string class, including how to call methods like size() on string objects and view documentation in the IDE.
- Brief explanations of core C++ concepts like variables, functions, comments, and basic syntax rules.
The document provides an introduction to C++ programming, including:
- Getting started instructions for using the terminals in room B27 or the SCC to run C++ code.
- An overview of Code::Blocks, the integrated development environment that will be used for writing and compiling C++ programs.
- A first "Hello, World!" C++ program that introduces basic C++ syntax like main(), cout, headers, and comments.
- Demonstrations of using C++ strings, including accessing string methods through auto-completion and printing the string size.
- Brief explanations of core C++ concepts like variables, functions, comments, and basic syntax rules.
In this deck from the Swiss HPC Conference, Gerd Buttner from Airbus presents: Innovating the Future of Flight.
"As a proven leader in the global aerospace sector, Airbus designs, produces and delivers innovative solutions with the aim to create a better-connected, safer and more prosperous world. These cutting-edge products and services – which span the commercial aircraft, helicopter, defence, security and space segments – benefit our wide-ranging expertise and continued emphasis on innovation."
Watch the video: https://wp.me/p3RLHQ-ke5
Learn more: http://airbus.com
and
http://hpcadvisorycouncil.com/events/2019/swiss-workshop/agenda.php
Sign up for our insideHPC Newsletter: http://insidehpc.com/newsletter
The document summarizes the speaker's experience at the de:code 2019 technical conference hosted by Microsoft. It discusses several sessions that were of interest, including Windows containers, Virtual Kubelet which allows Kubernetes to manage non-node resources, Kubernetes-based event-driven autoscaling (KEDA), and NetApp services. It also provides a demo of using Virtual Kubelet to run both Linux and Windows containers on AKS clusters through Azure container instances, showing how the pods are scheduled on virtual nodes.
How to deploy machine learning models into productionDataWorks Summit
Data scientists spend a lot of time on data cleaning and munging, so that they can finally start with the fun part of their job: building models. After you have engineered the features and tested different models, you see how the prediction performance improves. However, the job is not done when you have a high performing model. The deployment of your models is a crucial step in the overall workflow and it is the point in time when your models actually become useful to your company.
In this session you will learn about various possibilities and best practices to bring machine learning models into production environments. The goal is not only to make live prediction calls or have the models available as REST API, but also what needs to be considered to maintain them. This talk will focus on solutions with Python (flask, Cloud Foundry, Docker, and more) and the well established ML packages such as Spark MLlib, scikit-learn, and xgboost, but the concepts can be easily transferred to other languages and frameworks.
Speaker
Sumit Goyal, IBM, Software Engineer
FHIR-first development of healthcare applicationsHealthDev
Nikolai Ryzhikov, CTO of Health Samurai and lead of the FHIR Storage and Analytics track. Nikolai talks about the FHIR-first development of healthcare applications and the differences between using FHIR for new healthcare solutions versus interoperability
C++ tutorial outlines the steps to get started with C++ programming using Code::Blocks IDE on BU terminals and personal laptops. It discusses downloading and setting up Code::Blocks, writing a simple "Hello World" program, basic C++ syntax like variables, data types, and functions, and an introduction to classes using the string class as an example. The document provides a high-level overview of topics that will be covered in more depth in later parts of the C++ tutorial.
Kubernetes platform evolution at Audi Business Innovation started in 2016 with a PoC on AWS and grew to support over 1000 containers and 60 development teams by early 2018. Two outages occurred due to cluster upgrades and issues with the CNI plugin. Lessons learned included implementing a recovery plan using GitOps with Helm for deployments, monitoring, and backing up all configuration and data. The presentation emphasized choosing important work over urgent tasks, listening to feedback, and investing in relationships between people.
ANSI ISO C Professional Programmer S HandbookNicole Heredia
This chapter introduces the ANSI/ISO C++ Professional Programmer's Handbook. It discusses:
1. The origins of C++, which began in the late 1970s as an extension of C to support object-oriented programming.
2. The establishment of the ANSI committee in 1989 to standardize C++. This involved adopting an existing reference as a baseline and allowing the language to mature through feedback from users.
3. An overview of the book's contents, including discussions of language features like templates and exceptions, object-oriented design, and compatibility with C. The target audience is experienced C++ programmers.
The is a step by step turtorial for bluemix hadoop user from creating hadoop service, management with Ambari, explore HDFS, using WebHDFS API, conneting with R Cosole.
You can also learn runing liner regression with the airline.csv sample data and running k-means with the IRIS sample data on Bluemix hadoop.
Effective replacement of dynamic polymorphism with std::variantMateusz Pusz
These are the slides from my ACCU 2019 talk. You can find the recording here: https://www.youtube.com/watch?v=JGYxOieiZnY. All my other talks can be found here: https://train-it.eu/resources.
---
This short talk presents how easy it is to replace some cases of dynamic polymorphism with std::variant. During the lecture, we will analyze and compare a few implementations of the same simple Finite State Machine. It turns up that variant-based code is not only much faster but also it gives us the opportunity to define our interfaces and program flow much better. The talk will end up with the discussion of pros and cons of each approach and will try to give guidelines on when to use them.
Cloud-Native Application and KubernetesAlex Glikson
Guest lecture on Cloud-Native Applications and Kubernetes, in the Advanced Cloud Computing course (15-719) at the Carnegie Mellon University, February 2019.
C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...bhargavi804095
C++ is a cross-platform language that can be used to create high-performance applications.
C++ was developed by Bjarne Stroustrup, as an extension to the C language.
C++ gives programmers a high level of control over system resources and memory.
MS Day EPITA 2010: Visual Studio 2010 et Framework .NET 4.0Thomas Conté
This document summarizes the history and features of Microsoft's .NET Framework. It discusses the major releases from .NET 1.0 in 2002 through the current .NET 4.0. For each release, it highlights new capabilities like Windows Forms, ASP.NET, WPF, WCF, and LINQ. It also summarizes new areas in .NET 4.0 like parallel computing, the dynamic language runtime, and improvements to ADO.NET, Entity Framework, and Windows Workflow Foundation.
Assisted code review with source{d} lookoutsource{d}
Ensuring that a codebase is consistent in style is both hard and costly, yet it is extremely important for maintainability and to reduce technical debt. This problem is one of the many pain points we are currently tackling with source{d} Lookout, our brand new assisted code review framework.
The purpose of source{d} Lookout is to bring assisted code review to anyone in an easy-to-setup, easy-to-use, easy-to-extend fashion. To achieve that, source{d} Lookout watches Github repos and triggers a set of analyzers when new code is sent for review or pushed.
As a data scientist I frequently need to create web apps to provide interactive functionality, deliver data APIs or simply publish results. It is now easier than ever to deploy your data driven web app by using cloud based application platforms to do the heavy lifting. Cloud Foundry (http://cloudfoundry.org) is an open source public and private cloud platform that enables simple app deployment, scaling and connectivity to data services like PostgreSQL, MongoDB, Redis and Cassandra.
Resources: http://www.ianhuston.net/2015/01/cloud-foundry-for-data-science-talk/
This document discusses a presentation given by Shoichiro Sakaigawa of Pumpkin Heads Co., Ltd. on June 11, 2018 about using IBM Cloud Kubernetes Services for cloud native technology use cases combined with DevOps practices. The presentation covered topics like Docker, Kubernetes, IBM Cloud Kubernetes Service, OpenWhisk, OpenShift, CI/CD pipelines, and IBM's DevOps toolchain.
C++ CoreHard Autumn 2018. Создание пакетов для открытых библиотек через conan...corehard_by
Использование сторонних библиотек в языке C++ никогда не было простым - необходимо было правильно собрать их, имея дело с различными системами сборки, но с появлением пакетного менеджера conan.io процесс стал намного проще, так что теперь осталось только сделать пакеты для нужным библиотек, и в этом поможет команда bincrafter-ов.
Streaming Topic Model Training and Inference with Apache FlinkDataWorks Summit
Analyzing streams of text data to extract topics is an important task for getting useful insights to be leveraged in subsequent workflows. For example, extracting topics from text to be continuously ingested into a search engine can be useful to tag documents with important
keywords or concepts to be used at search time. Another use case is doing analysis of support tickets to get insights on the most common problems for customers.
In this talk we illustrate how to use Apache Flink's Dynamic processing and Stateful streaming capabilities to continuously train topic models from unlabelled text and use such models to extract topics from the data itself. Such topic models will be built leveraging distributed representations of words and documents. We’ll be seeing as to how this can be all done in a pure streaming fashion without having to resort to a Lambda Architecture kind’a setup. An earlier version of this talk was presented at Flink Forward Berlin 2018.
The document provides an introduction to C++ programming, including:
- Getting started instructions for using the terminals in room B27 or the SCC to run C++ code.
- An overview of Code::Blocks, the integrated development environment that will be used for writing and compiling C++ programs.
- A first "Hello, World!" C++ program that introduces basic C++ syntax like main(), cout, headers, and comments.
- Demonstrations of C++'s string class, including how to call methods like size() on string objects and view documentation in the IDE.
- Brief explanations of core C++ concepts like variables, functions, comments, and basic syntax rules.
The document provides an introduction to C++ programming, including:
- Getting started instructions for using the terminals in room B27 or the SCC to run C++ code.
- An overview of Code::Blocks, the integrated development environment that will be used for writing and compiling C++ programs.
- A first "Hello, World!" C++ program that introduces basic C++ syntax like main(), cout, headers, and comments.
- Demonstrations of using C++ strings, including accessing string methods through auto-completion and printing the string size.
- Brief explanations of core C++ concepts like variables, functions, comments, and basic syntax rules.
In this deck from the Swiss HPC Conference, Gerd Buttner from Airbus presents: Innovating the Future of Flight.
"As a proven leader in the global aerospace sector, Airbus designs, produces and delivers innovative solutions with the aim to create a better-connected, safer and more prosperous world. These cutting-edge products and services – which span the commercial aircraft, helicopter, defence, security and space segments – benefit our wide-ranging expertise and continued emphasis on innovation."
Watch the video: https://wp.me/p3RLHQ-ke5
Learn more: http://airbus.com
and
http://hpcadvisorycouncil.com/events/2019/swiss-workshop/agenda.php
Sign up for our insideHPC Newsletter: http://insidehpc.com/newsletter
The document summarizes the speaker's experience at the de:code 2019 technical conference hosted by Microsoft. It discusses several sessions that were of interest, including Windows containers, Virtual Kubelet which allows Kubernetes to manage non-node resources, Kubernetes-based event-driven autoscaling (KEDA), and NetApp services. It also provides a demo of using Virtual Kubelet to run both Linux and Windows containers on AKS clusters through Azure container instances, showing how the pods are scheduled on virtual nodes.
How to deploy machine learning models into productionDataWorks Summit
Data scientists spend a lot of time on data cleaning and munging, so that they can finally start with the fun part of their job: building models. After you have engineered the features and tested different models, you see how the prediction performance improves. However, the job is not done when you have a high performing model. The deployment of your models is a crucial step in the overall workflow and it is the point in time when your models actually become useful to your company.
In this session you will learn about various possibilities and best practices to bring machine learning models into production environments. The goal is not only to make live prediction calls or have the models available as REST API, but also what needs to be considered to maintain them. This talk will focus on solutions with Python (flask, Cloud Foundry, Docker, and more) and the well established ML packages such as Spark MLlib, scikit-learn, and xgboost, but the concepts can be easily transferred to other languages and frameworks.
Speaker
Sumit Goyal, IBM, Software Engineer
FHIR-first development of healthcare applicationsHealthDev
Nikolai Ryzhikov, CTO of Health Samurai and lead of the FHIR Storage and Analytics track. Nikolai talks about the FHIR-first development of healthcare applications and the differences between using FHIR for new healthcare solutions versus interoperability
C++ tutorial outlines the steps to get started with C++ programming using Code::Blocks IDE on BU terminals and personal laptops. It discusses downloading and setting up Code::Blocks, writing a simple "Hello World" program, basic C++ syntax like variables, data types, and functions, and an introduction to classes using the string class as an example. The document provides a high-level overview of topics that will be covered in more depth in later parts of the C++ tutorial.
Kubernetes platform evolution at Audi Business Innovation started in 2016 with a PoC on AWS and grew to support over 1000 containers and 60 development teams by early 2018. Two outages occurred due to cluster upgrades and issues with the CNI plugin. Lessons learned included implementing a recovery plan using GitOps with Helm for deployments, monitoring, and backing up all configuration and data. The presentation emphasized choosing important work over urgent tasks, listening to feedback, and investing in relationships between people.
ANSI ISO C Professional Programmer S HandbookNicole Heredia
This chapter introduces the ANSI/ISO C++ Professional Programmer's Handbook. It discusses:
1. The origins of C++, which began in the late 1970s as an extension of C to support object-oriented programming.
2. The establishment of the ANSI committee in 1989 to standardize C++. This involved adopting an existing reference as a baseline and allowing the language to mature through feedback from users.
3. An overview of the book's contents, including discussions of language features like templates and exceptions, object-oriented design, and compatibility with C. The target audience is experienced C++ programmers.
The is a step by step turtorial for bluemix hadoop user from creating hadoop service, management with Ambari, explore HDFS, using WebHDFS API, conneting with R Cosole.
You can also learn runing liner regression with the airline.csv sample data and running k-means with the IRIS sample data on Bluemix hadoop.
Effective replacement of dynamic polymorphism with std::variantMateusz Pusz
These are the slides from my ACCU 2019 talk. You can find the recording here: https://www.youtube.com/watch?v=JGYxOieiZnY. All my other talks can be found here: https://train-it.eu/resources.
---
This short talk presents how easy it is to replace some cases of dynamic polymorphism with std::variant. During the lecture, we will analyze and compare a few implementations of the same simple Finite State Machine. It turns up that variant-based code is not only much faster but also it gives us the opportunity to define our interfaces and program flow much better. The talk will end up with the discussion of pros and cons of each approach and will try to give guidelines on when to use them.
Cloud-Native Application and KubernetesAlex Glikson
Guest lecture on Cloud-Native Applications and Kubernetes, in the Advanced Cloud Computing course (15-719) at the Carnegie Mellon University, February 2019.
C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...bhargavi804095
C++ is a cross-platform language that can be used to create high-performance applications.
C++ was developed by Bjarne Stroustrup, as an extension to the C language.
C++ gives programmers a high level of control over system resources and memory.
MS Day EPITA 2010: Visual Studio 2010 et Framework .NET 4.0Thomas Conté
This document summarizes the history and features of Microsoft's .NET Framework. It discusses the major releases from .NET 1.0 in 2002 through the current .NET 4.0. For each release, it highlights new capabilities like Windows Forms, ASP.NET, WPF, WCF, and LINQ. It also summarizes new areas in .NET 4.0 like parallel computing, the dynamic language runtime, and improvements to ADO.NET, Entity Framework, and Windows Workflow Foundation.
Assisted code review with source{d} lookoutsource{d}
Ensuring that a codebase is consistent in style is both hard and costly, yet it is extremely important for maintainability and to reduce technical debt. This problem is one of the many pain points we are currently tackling with source{d} Lookout, our brand new assisted code review framework.
The purpose of source{d} Lookout is to bring assisted code review to anyone in an easy-to-setup, easy-to-use, easy-to-extend fashion. To achieve that, source{d} Lookout watches Github repos and triggers a set of analyzers when new code is sent for review or pushed.
As a data scientist I frequently need to create web apps to provide interactive functionality, deliver data APIs or simply publish results. It is now easier than ever to deploy your data driven web app by using cloud based application platforms to do the heavy lifting. Cloud Foundry (http://cloudfoundry.org) is an open source public and private cloud platform that enables simple app deployment, scaling and connectivity to data services like PostgreSQL, MongoDB, Redis and Cassandra.
Resources: http://www.ianhuston.net/2015/01/cloud-foundry-for-data-science-talk/
This document discusses a presentation given by Shoichiro Sakaigawa of Pumpkin Heads Co., Ltd. on June 11, 2018 about using IBM Cloud Kubernetes Services for cloud native technology use cases combined with DevOps practices. The presentation covered topics like Docker, Kubernetes, IBM Cloud Kubernetes Service, OpenWhisk, OpenShift, CI/CD pipelines, and IBM's DevOps toolchain.
C++ CoreHard Autumn 2018. Создание пакетов для открытых библиотек через conan...corehard_by
Использование сторонних библиотек в языке C++ никогда не было простым - необходимо было правильно собрать их, имея дело с различными системами сборки, но с появлением пакетного менеджера conan.io процесс стал намного проще, так что теперь осталось только сделать пакеты для нужным библиотек, и в этом поможет команда bincrafter-ов.
C++ CoreHard Autumn 2018. Actors vs CSP vs Tasks vs ... - Евгений Охотниковcorehard_by
На предыдущих конференциях C++ CoreHard автор доклада рассказывал про Модель Акторов и опыт ее использования в C++. Но Модель Акторов -- это далеко не единственный способ борьбы со сложностью при работе с многопоточностью. Давайте попробуем поговорить о том, что еще можно применить и как это может выглядеть в C++.
C++ CoreHard Autumn 2018. Знай свое "железо": иерархия памяти - Александр Титовcorehard_by
Если вам важна скорость работы ваших программ, то вы обязаны понимать, как работает ваше "железо". Современный процессор -- это сложное устройство, многие механизмы которого могут неочевидным образом влиять на скорость исполнения вашего кода. В докладе дается обзорное представление основных структур современного процессора и подробно рассматривается работа иерархии памяти. Будут освещены следующие темы: организация кэш-памяти, принцип локальности, предподкачка данных, нежелательное общее владение данными, а также программные техники для эффективной работы с памятью.
C++ CoreHard Autumn 2018. Информационная безопасность и разработка ПО - Евген...corehard_by
Информационная безопасность все больше из отдельной сферы плавно перетекает в разработку ПО. А значит «обычным» программистам приходится понимать те требования и терминологию, которые специалисты по безопасности уже давно знают и используют. CWE, CERT, MISRA, SAST– для «обычных» программистов это непонятные аббревиатуры. Поэтому в обзорном докладе мы попробуем рассказать простым языком об этих понятиях так, чтобы все разработчики начали уверенно ориентироваться в этой теме.
C++ CoreHard Autumn 2018. Заглядываем под капот «Поясов по C++» - Илья Шишковcorehard_by
Вот уже более двух лет мы создаём онлайн-специализацию по С++ на платформе Coursera. Её цель — обучить языку C++ с нуля до уровня, достаточного для решения практических задач, с которыми приходилось сталкиваться авторам в своей практике. В своём докладе я расскажу, как мы создаём наши онлайн-курсы, и уделю особое внимание техническим проблемам, которые нам пришлось решить в процессе создания автоматической системы проверки программ студентов.
C++ CoreHard Autumn 2018. Ускорение сборки C++ проектов, способы и последстви...corehard_by
В докладе обсуждаются способы улучшения времени сборки C++ проектов, опыт полученный в ходе ускорения сборки клиента и тулов World Of Tanks. Также описывается эффект, который они оказывают на организацию кодобазы (как позитивный, так и негативный) и затраты, которые необходимы для поддержки этих решений, т.к. не все они бесплатны. Методики, описываемые в докладе: ускорение линковки (Incremental Linking, Fastlink), ускорение компиляции(Include what you use, использование precompiled headers).
C++ CoreHard Autumn 2018. Метаклассы: воплощаем мечты в реальность - Сергей С...corehard_by
Доклад посвящён вопросам реализации пропозала Герба Саттера PR0707 (метаклассы в С++) за пределами компилятор - в виде отдельной утилиты. Будет продемонстрированы варианты использования метаклассов в реальной жизни, затронуты вопросы их реализации на базе Clang Frontend, а также возможные перспективы развития технологии и методики.
C++ CoreHard Autumn 2018. Что не умеет оптимизировать компилятор - Александр ...corehard_by
Все мы знаем, что компиляторы в настоящее время достаточно умные. И нам как программистам зачастую не нужно думать о каких-то незначительных оптимизациях - мы полагаемся на оптимизации компилятора. Что ж, настало время выяснить, действительно ли настолько компиляторы умны и узнать, в каких местах программист всё же (может быть) умнее.
C++ CoreHard Autumn 2018. Кодогенерация C++ кроссплатформенно. Продолжение - ...corehard_by
В докладе будет рассмотрена генерация кода при компиляции различных языковых конструкций, как простых, так и сложных, на различных платформах, как общераспространённых x86/x64, так и тех, которым уделяется меньше внимания: ARM, AVR. Также будут встречаться примеры для совсем экзотических процессоров вроде PowerPC и даже MicroBlaze. Основной упор будет делаться не на обработку данных, а именно на сопоставление различных конструкций кода с инструкциями целевых платформ.
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...corehard_by
What do threads, atomic variables, mutexes, and conditional variables have in common? They are the basic building blocks of any concurrent application in C++, which are even for the experienced C++ programmers a big challenge. This massively changed with C++17 and change even more with C++20/23. What did we get with C++17, what can we hope for with C++20/23? With C++17, most of the standard template library algorithms are available in sequential, parallel, and vectorised variants. With the upcoming standards, we can look forward to executors, transactional memory, significantly improved futures and coroutines. To make it short. These are just the highlights from the concurrent and parallel perspective. Thus there is the hope that in the future C++ abstractions such as executors, transactional memory, futures and coroutines are used and that threads, atomic variables, mutexes and condition variables are just implementation details.
C++ CoreHard Autumn 2018. Обработка списков на C++ в функциональном стиле - В...corehard_by
Язык C++, претерпев долгую эволюцию, обрёл ряд черт, характерных для функциональной парадигмы: функции стали полноправными объектами, над которыми могут выполняться операции, а аппарат шаблонов позволяет проводить вычисления на типах на этапе компиляции. Математический фундамент этих двух главных аспектов составляют, соответственно, ламбда-исчисление и теория категорий. Расширение языка этими средствами способствовало реализации на языке C++ ряда инструментов, известных из функционального программирования. Некоторые из этих реализаций вошли в стандартную библиотеку (std::function, std::bind), другие - в сторонние библиотеки, в том числе в коллекцию библиотек Boost (functional, hana). Важную роль в арсенале функционального программирования играют операции свёртки и развёртки, которые очевиднее всего определяются для списков, но также естественным образом обобщаются на другие индуктивные и коиндуктивные структуры данных. Например, суммирование списка чисел можно представить себе как свёртку списка по операции сложения, а построение списка простых множителей заданного целого числа - как развёртку. Обобщения свёртки и развёртки известны как анаморфизмы и катаморфизмы. Также в функциональном программировании находит применение понятие гиломорфизма - композиция развёртки некоторого объекта в коллекцию с последующей свёрткой её в новый объект. В докладе продемонстрировано, что свёртки, развёртки и их композиции допускают довольно простую реализацию на языке C++.
C++ Corehard Autumn 2018. Обучаем на Python, применяем на C++ - Павел Филоновcorehard_by
Доклад посвящен часто используемому шаблону в моих проектах по анализу данных, когда обучение и настройка моделей происходят с использованием python, а вот их запуск в промышленное использование на языке C++. Предлагается рассмотреть несколько учебных примеров реализации такого подхода, от простой линейной регрессии до обработки изображений с помощью нейронных сетей.
C++ CoreHard Autumn 2018. Asynchronous programming with ranges - Ivan Čukićcorehard_by
This talk will be about the design and implementation of a reactive programming model inspired by ranges that allows easy implementation of asynchronous and distributed software systems by writing code that looks like a sequence of ordinary range transformations like filter, transform, etc. This programming model will be demonstrated along with the implementation of a simple asynchronous web service where the whole system logic is defined as a chain of range transformations.
C++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia Kazakovacorehard_by
The document discusses how an IDE can help debug tricky C++ code without running it by leveraging tools to understand macros, types, templates, and overloads. It describes how an IDE could show the step-by-step substitution of macros, substitute typedefs one step at a time, debug template instantiations and constant expressions, explain overload resolution, and profile includes to optimize header usage. The presenter argues that tools are needed to make powerful C++ abstractions more accessible.
C++ CoreHard Autumn 2018. Полезный constexpr - Антон Полухинcorehard_by
В C++11 добавили новое ключевое слово - constexpr. Выглядит оно весьма невзрачно, да и на первый взгляд кажется, что смысла в нём маловато... Для чего же оно нужно, какие у него есть тайные супер способности и какую роль оно сыграет в дальнейшем развитии языка C++ - обо всём об этом мы и поговорим.
C++ CoreHard Autumn 2018. Text Formatting For a Future Range-Based Standard L...corehard_by
This document discusses range-based text formatting and proposes replacing existing approaches with a range-based solution. It suggests representing text as ranges and using range algorithms and functions for concatenation and formatting. This would allow treating different string types uniformly and flexibly while avoiding issues with current formatting methods like iostream manipulation and format strings. The document provides examples of formatting numbers and dates as ranges and constructing containers like std::string from multiple ranges.
Исключительная модель памяти. Алексей Ткаченко ➠ CoreHard Autumn 2019corehard_by
Память в компьютере - это не только гигабайты оперативной памяти в слоте, но и занятная абстракция. В докладе мы рассмотрим, как можно эту абстракцию использовать необычным образом для моделирования других абстракций - регистровых файлов периферийных устройств. Доклад будет полезен не только embedded-разработчикам, но и, возможно, заставит переосмыслить свой взгляд на память.
Как помочь и как помешать компилятору. Андрей Олейников ➠ CoreHard Autumn 2019corehard_by
Как правило, можно положиться на то, что компилятор оптимизирует результирующий бинарный файл так, чтобы она работала максимально быстро. Но компилятор не знает на каких данных и на каком железе программа будет запущена. Плюс хотелось бы, чтобы компиляция занимала приемлемое время. Из-за этого результат может оказаться субоптимальным. Предлагаю на примерах для LLVM посмотреть как можно подсказать компилятору как оптимизировать программу и сделать результат лучше или хуже.
Мы напишем простейший веб-сервис из клиента и сервера на C++. На этом C++ часть закончится, и пойдет настройка окружения и инфраструктуры. Мы обеспечим детерминируемость сборки и прогона тестов. Облегчим последующее обновление зависимых библиотек. Автоматизируем статические проверки, верификацию кода, прогон тестов. Обеспечим доступность сервиса, настроим инфраструктуру, сбалансируем нагрузку, добавим автоматическое и ручное масштабирование. И под конец мы настроим continious delivery таким образом, что код будет на продакшене через 5 минут после реквеста, при этом даже невалидные изменения и ошибки программиста не смогут повлиять на его работу.
Have you ever been confused by the myriad of choices offered by AWS for hosting a website or an API?
Lambda, Elastic Beanstalk, Lightsail, Amplify, S3 (and more!) can each host websites + APIs. But which one should we choose?
Which one is cheapest? Which one is fastest? Which one will scale to meet our needs?
Join me in this session as we dive into each AWS hosting service to determine which one is best for your scenario and explain why!
How information systems are built or acquired puts information, which is what they should be about, in a secondary place. Our language adapted accordingly, and we no longer talk about information systems but applications. Applications evolved in a way to break data into diverse fragments, tightly coupled with applications and expensive to integrate. The result is technical debt, which is re-paid by taking even bigger "loans", resulting in an ever-increasing technical debt. Software engineering and procurement practices work in sync with market forces to maintain this trend. This talk demonstrates how natural this situation is. The question is: can something be done to reverse the trend?
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...Fwdays
Direct losses from downtime in 1 minute = $5-$10 thousand dollars. Reputation is priceless.
As part of the talk, we will consider the architectural strategies necessary for the development of highly loaded fintech solutions. We will focus on using queues and streaming to efficiently work and manage large amounts of data in real-time and to minimize latency.
We will focus special attention on the architectural patterns used in the design of the fintech system, microservices and event-driven architecture, which ensure scalability, fault tolerance, and consistency of the entire system.
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...Jason Yip
The typical problem in product engineering is not bad strategy, so much as “no strategy”. This leads to confusion, lack of motivation, and incoherent action. The next time you look for a strategy and find an empty space, instead of waiting for it to be filled, I will show you how to fill it in yourself. If you’re wrong, it forces a correction. If you’re right, it helps create focus. I’ll share how I’ve approached this in the past, both what works and lessons for what didn’t work so well.
Dandelion Hashtable: beyond billion requests per second on a commodity serverAntonios Katsarakis
This slide deck presents DLHT, a concurrent in-memory hashtable. Despite efforts to optimize hashtables, that go as far as sacrificing core functionality, state-of-the-art designs still incur multiple memory accesses per request and block request processing in three cases. First, most hashtables block while waiting for data to be retrieved from memory. Second, open-addressing designs, which represent the current state-of-the-art, either cannot free index slots on deletes or must block all requests to do so. Third, index resizes block every request until all objects are copied to the new index. Defying folklore wisdom, DLHT forgoes open-addressing and adopts a fully-featured and memory-aware closed-addressing design based on bounded cache-line-chaining. This design offers lock-free index operations and deletes that free slots instantly, (2) completes most requests with a single memory access, (3) utilizes software prefetching to hide memory latencies, and (4) employs a novel non-blocking and parallel resizing. In a commodity server and a memory-resident workload, DLHT surpasses 1.6B requests per second and provides 3.5x (12x) the throughput of the state-of-the-art closed-addressing (open-addressing) resizable hashtable on Gets (Deletes).
AppSec PNW: Android and iOS Application Security with MobSFAjin Abraham
Mobile Security Framework - MobSF is a free and open source automated mobile application security testing environment designed to help security engineers, researchers, developers, and penetration testers to identify security vulnerabilities, malicious behaviours and privacy concerns in mobile applications using static and dynamic analysis. It supports all the popular mobile application binaries and source code formats built for Android and iOS devices. In addition to automated security assessment, it also offers an interactive testing environment to build and execute scenario based test/fuzz cases against the application.
This talk covers:
Using MobSF for static analysis of mobile applications.
Interactive dynamic security assessment of Android and iOS applications.
Solving Mobile app CTF challenges.
Reverse engineering and runtime analysis of Mobile malware.
How to shift left and integrate MobSF/mobsfscan SAST and DAST in your build pipeline.
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyScyllaDB
Freshworks creates AI-boosted business software that helps employees work more efficiently and effectively. Managing data across multiple RDBMS and NoSQL databases was already a challenge at their current scale. To prepare for 10X growth, they knew it was time to rethink their database strategy. Learn how they architected a solution that would simplify scaling while keeping costs under control.
Main news related to the CCS TSI 2023 (2023/1695)Jakub Marek
An English 🇬🇧 translation of a presentation to the speech I gave about the main changes brought by CCS TSI 2023 at the biggest Czech conference on Communications and signalling systems on Railways, which was held in Clarion Hotel Olomouc from 7th to 9th November 2023 (konferenceszt.cz). Attended by around 500 participants and 200 on-line followers.
The original Czech 🇨🇿 version of the presentation can be found here: https://www.slideshare.net/slideshow/hlavni-novinky-souvisejici-s-ccs-tsi-2023-2023-1695/269688092 .
The videorecording (in Czech) from the presentation is available here: https://youtu.be/WzjJWm4IyPk?si=SImb06tuXGb30BEH .
Taking AI to the Next Level in Manufacturing.pdfssuserfac0301
Read Taking AI to the Next Level in Manufacturing to gain insights on AI adoption in the manufacturing industry, such as:
1. How quickly AI is being implemented in manufacturing.
2. Which barriers stand in the way of AI adoption.
3. How data quality and governance form the backbone of AI.
4. Organizational processes and structures that may inhibit effective AI adoption.
6. Ideas and approaches to help build your organization's AI strategy.
Monitoring and Managing Anomaly Detection on OpenShift.pdfTosin Akinosho
Monitoring and Managing Anomaly Detection on OpenShift
Overview
Dive into the world of anomaly detection on edge devices with our comprehensive hands-on tutorial. This SlideShare presentation will guide you through the entire process, from data collection and model training to edge deployment and real-time monitoring. Perfect for those looking to implement robust anomaly detection systems on resource-constrained IoT/edge devices.
Key Topics Covered
1. Introduction to Anomaly Detection
- Understand the fundamentals of anomaly detection and its importance in identifying unusual behavior or failures in systems.
2. Understanding Edge (IoT)
- Learn about edge computing and IoT, and how they enable real-time data processing and decision-making at the source.
3. What is ArgoCD?
- Discover ArgoCD, a declarative, GitOps continuous delivery tool for Kubernetes, and its role in deploying applications on edge devices.
4. Deployment Using ArgoCD for Edge Devices
- Step-by-step guide on deploying anomaly detection models on edge devices using ArgoCD.
5. Introduction to Apache Kafka and S3
- Explore Apache Kafka for real-time data streaming and Amazon S3 for scalable storage solutions.
6. Viewing Kafka Messages in the Data Lake
- Learn how to view and analyze Kafka messages stored in a data lake for better insights.
7. What is Prometheus?
- Get to know Prometheus, an open-source monitoring and alerting toolkit, and its application in monitoring edge devices.
8. Monitoring Application Metrics with Prometheus
- Detailed instructions on setting up Prometheus to monitor the performance and health of your anomaly detection system.
9. What is Camel K?
- Introduction to Camel K, a lightweight integration framework built on Apache Camel, designed for Kubernetes.
10. Configuring Camel K Integrations for Data Pipelines
- Learn how to configure Camel K for seamless data pipeline integrations in your anomaly detection workflow.
11. What is a Jupyter Notebook?
- Overview of Jupyter Notebooks, an open-source web application for creating and sharing documents with live code, equations, visualizations, and narrative text.
12. Jupyter Notebooks with Code Examples
- Hands-on examples and code snippets in Jupyter Notebooks to help you implement and test anomaly detection models.
Your One-Stop Shop for Python Success: Top 10 US Python Development Providersakankshawande
Simplify your search for a reliable Python development partner! This list presents the top 10 trusted US providers offering comprehensive Python development services, ensuring your project's success from conception to completion.
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...Alex Pruden
Folding is a recent technique for building efficient recursive SNARKs. Several elegant folding protocols have been proposed, such as Nova, Supernova, Hypernova, Protostar, and others. However, all of them rely on an additively homomorphic commitment scheme based on discrete log, and are therefore not post-quantum secure. In this work we present LatticeFold, the first lattice-based folding protocol based on the Module SIS problem. This folding protocol naturally leads to an efficient recursive lattice-based SNARK and an efficient PCD scheme. LatticeFold supports folding low-degree relations, such as R1CS, as well as high-degree relations, such as CCS. The key challenge is to construct a secure folding protocol that works with the Ajtai commitment scheme. The difficulty, is ensuring that extracted witnesses are low norm through many rounds of folding. We present a novel technique using the sumcheck protocol to ensure that extracted witnesses are always low norm no matter how many rounds of folding are used. Our evaluation of the final proof system suggests that it is as performant as Hypernova, while providing post-quantum security.
Paper Link: https://eprint.iacr.org/2024/257
"Scaling RAG Applications to serve millions of users", Kevin GoedeckeFwdays
How we managed to grow and scale a RAG application from zero to thousands of users in 7 months. Lessons from technical challenges around managing high load for LLMs, RAGs and Vector databases.
What is an RPA CoE? Session 1 – CoE VisionDianaGray10
In the first session, we will review the organization's vision and how this has an impact on the COE Structure.
Topics covered:
• The role of a steering committee
• How do the organization’s priorities determine CoE Structure?
Speaker:
Chris Bolin, Senior Intelligent Automation Architect Anika Systems
Essentials of Automations: Exploring Attributes & Automation ParametersSafe Software
Building automations in FME Flow can save time, money, and help businesses scale by eliminating data silos and providing data to stakeholders in real-time. One essential component to orchestrating complex automations is the use of attributes & automation parameters (both formerly known as “keys”). In fact, it’s unlikely you’ll ever build an Automation without using these components, but what exactly are they?
Attributes & automation parameters enable the automation author to pass data values from one automation component to the next. During this webinar, our FME Flow Specialists will cover leveraging the three types of these output attributes & parameters in FME Flow: Event, Custom, and Automation. As a bonus, they’ll also be making use of the Split-Merge Block functionality.
You’ll leave this webinar with a better understanding of how to maximize the potential of automations by making use of attributes & automation parameters, with the ultimate goal of setting your enterprise integration workflows up on autopilot.
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
Implementing Physical Units Library for C++. Mateusz Pusz.CoreHard Spring 2019
1. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 1/184
Mateusz Pusz
May 25, 2019
Implementing a Physical Units
Library for C++
2. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 2/184
A famous motivating example
3. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 3/184
• Robotic space probe launched by NASA on
December 11, 1998
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
The Mars Climate Orbiter
3
4. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 4/184
• Robotic space probe launched by NASA on
December 11, 1998
• Project costs: $327.6 million
– spacecra development: $193.1 million
– launching it: $91.7 million
– mission operations: $42.8 million
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
The Mars Climate Orbiter
3
5. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 5/184
• Robotic space probe launched by NASA on
December 11, 1998
• Project costs: $327.6 million
– spacecra development: $193.1 million
– launching it: $91.7 million
– mission operations: $42.8 million
• Mars Climate Orbiter began the planned
orbital insertion maneuver on September 23,
1999 at 09:00:46 UTC
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
The Mars Climate Orbiter
3
6. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 6/184
7. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 7/184
8. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 8/184
• Space probe went out of radio contact when it passed behind Mars at 09:04:52 UTC, 49 seconds earlier
than expected
• Communication was never reestablished
• The spacecra disintegrated due to atmospheric stresses
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
The Mars Climate Orbiter
6
9. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 9/184
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
What went wrong?
7
10. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 10/184
• The primary cause of this discrepancy was that
– one piece of ground so ware supplied by Lockheed Martin produced results in a United States
customary unit, contrary to its So ware Interface Specification (SIS)
– second system, supplied by NASA, expected those results to be in SI units, in accordance with the
SIS
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
What went wrong?
7
11. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 11/184
• The primary cause of this discrepancy was that
– one piece of ground so ware supplied by Lockheed Martin produced results in a United States
customary unit, contrary to its So ware Interface Specification (SIS)
– second system, supplied by NASA, expected those results to be in SI units, in accordance with the
SIS
• Specifically
– so ware that calculated the total impulse produced by thruster firings calculated results in pound-
seconds
– the trajectory calculation so ware then used these results to update the predicted position of the
spacecra and expected it to be in newton-seconds
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
What went wrong?
7
12. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 12/184
13. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 13/184
Why do I care?
ANOTHER EXAMPLE
14. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 14/184
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
A long time ago in a galaxy far far away...
10
15. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 15/184
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
A long time ago in a galaxy far far away...
10
16. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 16/184
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Tactical Flight Computer
11
17. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 17/184
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Tactical Flight Computer
12
18. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 18/184
void DistanceBearing(double lat1, double lon1,
double lat2, double lon2,
double *Distance, double *Bearing);
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
What is the correct order?
13
19. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 19/184
void DistanceBearing(double lat1, double lon1,
double lat2, double lon2,
double *Distance, double *Bearing);
void FindLatitudeLongitude(double Lat, double Lon,
double Bearing, double Distance,
double *lat_out, double *lon_out);
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
What is the correct order?
13
20. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 20/184
void DistanceBearing(double lat1, double lon1,
double lat2, double lon2,
double *Distance, double *Bearing);
void FindLatitudeLongitude(double Lat, double Lon,
double Bearing, double Distance,
double *lat_out, double *lon_out);
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
What is the correct order?
13
21. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 21/184
double GlidePolar::MacCreadyAltitude(double emcready,
double Distance,
const double Bearing,
const double WindSpeed,
const double WindBearing,
double *BestCruiseTrack,
double *VMacCready,
const bool isFinalGlide,
double *TimeToGo,
const double AltitudeAboveTarget,
const double cruise_efficiency,
const double TaskAltDiff);
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
double - an ultimate type to express quantity
14
22. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 22/184
// Air Density(kg/m3) from relative humidity(%),
// temperature(°C) and absolute pressure(Pa)
double AirDensity(double hr, double temp, double abs_press)
{
return (1/(287.06*(temp+273.15))) *
(abs_press - 230.617 * hr * exp((17.5043*temp)/(241.2+temp)));
}
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
We shouldn't write the code like that anymore
15
23. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 23/184
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
DID YOU EVER HAVE TO WRITE THE CODE THIS WAY?
16
24. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 24/184
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Why do we write our code this way?
17
25. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 25/184
• No support in the C++ Standard Library
– std::chrono helped a lot for time and duration
– date support comes in C++20
– still not enough for full dimensional analysis
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Why do we write our code this way?
17
26. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 26/184
• No support in the C++ Standard Library
– std::chrono helped a lot for time and duration
– date support comes in C++20
– still not enough for full dimensional analysis
• Lack of good alternatives
– poor user experience (i.e. compilation errors)
– heavy dependencies (i.e. Boost.Units)
– custom 3rd party libraries o en not allowed in production code
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Why do we write our code this way?
17
27. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 27/184
• No support in the C++ Standard Library
– std::chrono helped a lot for time and duration
– date support comes in C++20
– still not enough for full dimensional analysis
• Lack of good alternatives
– poor user experience (i.e. compilation errors)
– heavy dependencies (i.e. Boost.Units)
– custom 3rd party libraries o en not allowed in production code
• Implementing a good library by ourselves is hard
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Why do we write our code this way?
17
28. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 28/184
• No support in the C++ Standard Library
– std::chrono helped a lot for time and duration
– date support comes in C++20
– still not enough for full dimensional analysis
• Lack of good alternatives
– poor user experience (i.e. compilation errors)
– heavy dependencies (i.e. Boost.Units)
– custom 3rd party libraries o en not allowed in production code
• Implementing a good library by ourselves is hard
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Why do we write our code this way?
Let's do something about that!
17
29. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 29/184
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
CURRENT STATE
R E V I E W O F E X I S T I N G S O L U T I O N S
18
30. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 30/184
/* velocity */ avg_speed(/* length */ distance, /* time */ duration)
{
return distance / duration;
}
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Toy example
19
31. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 31/184
/* velocity */ avg_speed(/* length */ distance, /* time */ duration)
{
return distance / duration;
}
const auto kmph = avg_speed(/* 220 km */, /* 2 hours */);
std::cout << /* kmph */ << " km/hn";
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Toy example
19
32. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 32/184
/* velocity */ avg_speed(/* length */ distance, /* time */ duration)
{
return distance / duration;
}
const auto kmph = avg_speed(/* 220 km */, /* 2 hours */);
std::cout << /* kmph */ << " km/hn";
const auto mph = avg_speed(/* 140 miles */, /* 2 hours */);
std::cout << /* mph */ << " mphn";
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Toy example
19
33. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 33/184
/* velocity */ avg_speed(/* length */ distance, /* time */ duration)
{
return distance / duration;
}
const auto kmph = avg_speed(/* 220 km */, /* 2 hours */);
std::cout << /* kmph */ << " km/hn";
const auto mph = avg_speed(/* 140 miles */, /* 2 hours */);
std::cout << /* mph */ << " mphn";
• Compile time safety to make sure that the result is of a correct dimension
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Toy example
19
34. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 34/184
/* velocity */ avg_speed(/* length */ distance, /* time */ duration)
{
return distance / duration;
}
const auto kmph = avg_speed(/* 220 km */, /* 2 hours */);
std::cout << /* kmph */ << " km/hn";
const auto mph = avg_speed(/* 140 miles */, /* 2 hours */);
std::cout << /* mph */ << " mphn";
• Compile time safety to make sure that the result is of a correct dimension
• Support for multiple units and unit prefixes
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Toy example
19
35. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 35/184
/* velocity */ avg_speed(/* length */ distance, /* time */ duration)
{
return distance / duration;
}
const auto kmph = avg_speed(/* 220 km */, /* 2 hours */);
std::cout << /* kmph */ << " km/hn";
const auto mph = avg_speed(/* 140 miles */, /* 2 hours */);
std::cout << /* mph */ << " mphn";
• Compile time safety to make sure that the result is of a correct dimension
• Support for multiple units and unit prefixes
• No runtime overhead
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Toy example
19
36. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 36/184
/* velocity */ avg_speed(/* length */ distance, /* time */ duration)
{
return distance / duration;
}
const auto kmph = avg_speed(/* 220 km */, /* 2 hours */);
std::cout << /* kmph */ << " km/hn";
const auto mph = avg_speed(/* 140 miles */, /* 2 hours */);
std::cout << /* mph */ << " mphn";
• Compile time safety to make sure that the result is of a correct dimension
• Support for multiple units and unit prefixes
• No runtime overhead
• I/O output is out-of-scope for now (waiting for std::format())
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Toy example
19
37. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 37/184
• Boost.Units
– authors: Steven Watanabe, Matthias C. Schabel
– https://www.boost.org/doc/libs/1_69_0/doc/html/boost_units.html
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Existing solutions
20
38. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 38/184
• Boost.Units
– authors: Steven Watanabe, Matthias C. Schabel
– https://www.boost.org/doc/libs/1_69_0/doc/html/boost_units.html
• Units
– author: Nic Holthaus
– https://github.com/nholthaus/units
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Existing solutions
20
39. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 39/184
#include <boost/units/quantity.hpp>
#include <boost/units/systems/si/length.hpp>
#include <boost/units/systems/si/time.hpp>
#include <boost/units/systems/si/velocity.hpp>
#include <boost/units/systems/si/prefixes.hpp>
#include <boost/units/base_units/metric/hour.hpp>
#include <boost/units/base_units/us/mile.hpp>
#include <boost/units/make_scaled_unit.hpp>
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Boost.Units: Toy example
21
40. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 40/184
#include <boost/units/quantity.hpp>
#include <boost/units/systems/si/length.hpp>
#include <boost/units/systems/si/time.hpp>
#include <boost/units/systems/si/velocity.hpp>
#include <boost/units/systems/si/prefixes.hpp>
#include <boost/units/base_units/metric/hour.hpp>
#include <boost/units/base_units/us/mile.hpp>
#include <boost/units/make_scaled_unit.hpp>
namespace bu = boost::units;
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Boost.Units: Toy example
21
41. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 41/184
#include <boost/units/quantity.hpp>
#include <boost/units/systems/si/length.hpp>
#include <boost/units/systems/si/time.hpp>
#include <boost/units/systems/si/velocity.hpp>
#include <boost/units/systems/si/prefixes.hpp>
#include <boost/units/base_units/metric/hour.hpp>
#include <boost/units/base_units/us/mile.hpp>
#include <boost/units/make_scaled_unit.hpp>
namespace bu = boost::units;
using kilometer_base_unit = bu::make_scaled_unit<bu::si::length, bu::scale<10, bu::static_rational<3>>>::type;
using length_kilometer = kilometer_base_unit::unit_type;
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Boost.Units: Toy example
21
42. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 42/184
#include <boost/units/quantity.hpp>
#include <boost/units/systems/si/length.hpp>
#include <boost/units/systems/si/time.hpp>
#include <boost/units/systems/si/velocity.hpp>
#include <boost/units/systems/si/prefixes.hpp>
#include <boost/units/base_units/metric/hour.hpp>
#include <boost/units/base_units/us/mile.hpp>
#include <boost/units/make_scaled_unit.hpp>
namespace bu = boost::units;
using kilometer_base_unit = bu::make_scaled_unit<bu::si::length, bu::scale<10, bu::static_rational<3>>>::type;
using length_kilometer = kilometer_base_unit::unit_type;
using length_mile = bu::us::mile_base_unit::unit_type;
BOOST_UNITS_STATIC_CONSTANT(miles, length_mile);
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Boost.Units: Toy example
21
43. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 43/184
#include <boost/units/quantity.hpp>
#include <boost/units/systems/si/length.hpp>
#include <boost/units/systems/si/time.hpp>
#include <boost/units/systems/si/velocity.hpp>
#include <boost/units/systems/si/prefixes.hpp>
#include <boost/units/base_units/metric/hour.hpp>
#include <boost/units/base_units/us/mile.hpp>
#include <boost/units/make_scaled_unit.hpp>
namespace bu = boost::units;
using kilometer_base_unit = bu::make_scaled_unit<bu::si::length, bu::scale<10, bu::static_rational<3>>>::type;
using length_kilometer = kilometer_base_unit::unit_type;
using length_mile = bu::us::mile_base_unit::unit_type;
BOOST_UNITS_STATIC_CONSTANT(miles, length_mile);
using time_hour = bu::metric::hour_base_unit::unit_type;
BOOST_UNITS_STATIC_CONSTANT(hours, time_hour);
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Boost.Units: Toy example
21
44. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 44/184
constexpr bu::quantity<bu::si::velocity> avg_speed(bu::quantity<bu::si::length> d, bu::quantity<bu::si::time> t)
{
return d / t;
}
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Boost.Units: Toy example
22
45. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 45/184
constexpr bu::quantity<bu::si::velocity> avg_speed(bu::quantity<bu::si::length> d, bu::quantity<bu::si::time> t)
{
return d / t;
}
const auto v = avg_speed(bu::quantity<bu::si::length>(220 * bu::si::kilo * bu::si::meters),
bu::quantity<bu::si::time>(2 * hours));
using kilometers_per_hour = bu::divide_typeof_helper<length_kilometer, time_hour>::type;
bu::quantity<kilometers_per_hour> kmph(v);
std::cout << kmph.value() << " km/hn";
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Boost.Units: Toy example
22
46. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 46/184
constexpr bu::quantity<bu::si::velocity> avg_speed(bu::quantity<bu::si::length> d, bu::quantity<bu::si::time> t)
{
return d / t;
}
const auto v = avg_speed(bu::quantity<bu::si::length>(220 * bu::si::kilo * bu::si::meters),
bu::quantity<bu::si::time>(2 * hours));
using kilometers_per_hour = bu::divide_typeof_helper<length_kilometer, time_hour>::type;
bu::quantity<kilometers_per_hour> kmph(v);
std::cout << kmph.value() << " km/hn";
const auto v = avg_speed(bu::quantity<bu::si::length>(140 * miles),
bu::quantity<bu::si::time>(2 * hours));
using miles_per_hour = bu::divide_typeof_helper<length_mile, time_hour>::type;
bu::quantity<miles_per_hour> mph(v);
std::cout << mph.value() << " mphn";
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Boost.Units: Toy example
22
47. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 47/184
constexpr bu::quantity<bu::si::velocity> avg_speed(bu::quantity<bu::si::length> d, bu::quantity<bu::si::time> t)
{
return d / t;
}
const auto v = avg_speed(bu::quantity<bu::si::length>(220 * bu::si::kilo * bu::si::meters),
bu::quantity<bu::si::time>(2 * hours));
using kilometers_per_hour = bu::divide_typeof_helper<length_kilometer, time_hour>::type;
bu::quantity<kilometers_per_hour> kmph(v);
std::cout << kmph.value() << " km/hn";
const auto v = avg_speed(bu::quantity<bu::si::length>(140 * miles),
bu::quantity<bu::si::time>(2 * hours));
using miles_per_hour = bu::divide_typeof_helper<length_mile, time_hour>::type;
bu::quantity<miles_per_hour> mph(v);
std::cout << mph.value() << " mphn";
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Boost.Units: Toy example
Works, but runtime does unnecessary operations, and we may loose some
bits of information while doing that
22
48. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 48/184
• Too generic
template<typename Length, typename Time>
constexpr auto avg_speed(bu::quantity<Length> d, bu::quantity<Time> t)
{ return d / t; }
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Boost.Units: Toy example
23
49. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 49/184
• Too generic
template<typename Length, typename Time>
constexpr auto avg_speed(bu::quantity<Length> d, bu::quantity<Time> t)
{ return d / t; }
• Is it really a velocity dimension?
template<typename LengthSystem, typename Rep1, typename TimeSystem, typename Rep2>
constexpr auto avg_speed(bu::quantity<bu::unit<bu::length_dimension, LengthSystem>, Rep1> d,
bu::quantity<bu::unit<bu::time_dimension, TimeSystem>, Rep2> t)
{ return d / t; }
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Boost.Units: Toy example
23
50. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 50/184
• Too generic
template<typename Length, typename Time>
constexpr auto avg_speed(bu::quantity<Length> d, bu::quantity<Time> t)
{ return d / t; }
• Is it really a velocity dimension?
template<typename LengthSystem, typename Rep1, typename TimeSystem, typename Rep2>
constexpr auto avg_speed(bu::quantity<bu::unit<bu::length_dimension, LengthSystem>, Rep1> d,
bu::quantity<bu::unit<bu::time_dimension, TimeSystem>, Rep2> t)
{ return d / t; }
• Manually repeats built-in dimensional analysis logic
template<typename LengthSystem, typename Rep1, typename TimeSystem, typename Rep2>
constexpr bu::quantity<typename bu::divide_typeof_helper<bu::unit<bu::length_dimension, LengthSystem>,
bu::unit<bu::time_dimension, TimeSystem>>::type>
avg_speed(bu::quantity<bu::unit<bu::length_dimension, LengthSystem>, Rep1> d,
bu::quantity<bu::unit<bu::time_dimension, TimeSystem>, Rep2> t)
{ return d / t; }
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Boost.Units: Toy example
23
51. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 51/184
template<typename LengthSystem, typename Rep1, typename TimeSystem, typename Rep2>
constexpr auto avg_speed(bu::quantity<bu::unit<bu::length_dimension, LengthSystem>, Rep1> d,
bu::quantity<bu::unit<bu::time_dimension, TimeSystem>, Rep2> t);
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Boost.Units: Toy example
24
52. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 52/184
template<typename LengthSystem, typename Rep1, typename TimeSystem, typename Rep2>
constexpr auto avg_speed(bu::quantity<bu::unit<bu::length_dimension, LengthSystem>, Rep1> d,
bu::quantity<bu::unit<bu::time_dimension, TimeSystem>, Rep2> t);
const auto kmph = avg_speed(220 * bu::si::kilo * bu::si::meters, 2 * hours);
std::cout << kmph.value() << " km/hn";
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Boost.Units: Toy example
24
53. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 53/184
template<typename LengthSystem, typename Rep1, typename TimeSystem, typename Rep2>
constexpr auto avg_speed(bu::quantity<bu::unit<bu::length_dimension, LengthSystem>, Rep1> d,
bu::quantity<bu::unit<bu::time_dimension, TimeSystem>, Rep2> t);
const auto kmph = avg_speed(220 * bu::si::kilo * bu::si::meters, 2 * hours);
std::cout << kmph.value() << " km/hn";
const auto mph = avg_speed(140 * miles, 2 * hours);
std::cout << mph.value() << " mphn";
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Boost.Units: Toy example
24
54. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 54/184
• The widest adoption thanks to Boost
• A wide range of systems and base units
• High flexibility and extensibility
• constexpr usage helps in compile-time
• quantity can use any number-like type for its
representation
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Boost.Units: Summary
PROS
25
55. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 55/184
• The widest adoption thanks to Boost
• A wide range of systems and base units
• High flexibility and extensibility
• constexpr usage helps in compile-time
• quantity can use any number-like type for its
representation
• Pre-C++11 design
• Heavily relies on macros and Boost.MPL
• Domain and C++ experts only
– poor compile-time error messages
– no easy way to use non-SI units
– spread over too many small headers (hard to
compile a simple program)
– designed around custom unit systems
• Not possible to explicitly construct a quantity of
known unit from a plain value (even if no
truncation occurs)
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Boost.Units: Summary
PROS CONS
25
56. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 56/184
#include "units.h"
using namespace units::literals;
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Units: Toy example
26
57. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 57/184
#include "units.h"
using namespace units::literals;
template<typename Length, typename Time>
constexpr auto avg_speed(Length d, Time t)
{
const auto v = d / t;
return v;
}
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Units: Toy example
26
58. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 58/184
#include "units.h"
using namespace units::literals;
template<typename Length, typename Time>
constexpr auto avg_speed(Length d, Time t)
{
static_assert(units::traits::is_length_unit<Length>::value);
static_assert(units::traits::is_time_unit<Time>::value);
const auto v = d / t;
static_assert(units::traits::is_velocity_unit<decltype(v)>::value);
return v;
}
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Units: Toy example
26
59. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 59/184
#include "units.h"
using namespace units::literals;
template<typename Length, typename Time>
constexpr auto avg_speed(Length d, Time t)
{
static_assert(units::traits::is_length_unit<Length>::value);
static_assert(units::traits::is_time_unit<Time>::value);
const auto v = d / t;
static_assert(units::traits::is_velocity_unit<decltype(v)>::value);
return v;
}
• Not possible to define template arguments that will provide proper overload resolution because of
unit nesting
using meter_t = units::unit_t<units::unit<std::ratio<1>, units::category::length_unit>>;
using kilometer_t = units::unit_t<units::unit<std::ratio<1000, 1>, meter_t>, std::ratio<0, 1>, std::ratio<0, 1>>>;
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Units: Toy example
26
60. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 60/184
#include "units.h"
using namespace units::literals;
template<typename Length, typename Time,
typename = std::enable_if_t<units::traits::is_length_unit<Length>::value &&
units::traits::is_time_unit<Time>::value>>
constexpr auto avg_speed(Length d, Time t)
{
const auto v = d / t;
static_assert(units::traits::is_velocity_unit<decltype(v)>::value);
return v;
}
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Units: Toy example
27
61. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 61/184
#include "units.h"
using namespace units::literals;
template<typename Length, typename Time,
typename = std::enable_if_t<units::traits::is_length_unit<Length>::value &&
units::traits::is_time_unit<Time>::value>>
constexpr auto avg_speed(Length d, Time t)
{
const auto v = d / t;
static_assert(units::traits::is_velocity_unit<decltype(v)>::value);
return v;
}
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Units: Toy example
Using SFINAE in every single function template working with units is probably
too complicated or time consuming for an average user of the library
27
62. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 62/184
template<typename Length, typename Time>
constexpr auto avg_speed(Length d, Time t);
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Units: Toy example
28
63. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 63/184
template<typename Length, typename Time>
constexpr auto avg_speed(Length d, Time t);
const auto kmph = avg_speed(220_km, 2_hr);
std::cout << kmph.value() << " km/hn";
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Units: Toy example
28
64. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 64/184
template<typename Length, typename Time>
constexpr auto avg_speed(Length d, Time t);
const auto kmph = avg_speed(220_km, 2_hr);
std::cout << kmph.value() << " km/hn";
const auto mph = avg_speed(140_mi, 2_hr);
std::cout << mph.value() << " mphn";
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Units: Toy example
28
65. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 65/184
template<typename Length, typename Time>
constexpr auto avg_speed(Length d, Time t);
units::length::kilometer_t d(220);
units::time::hour_t t(2);
const auto kmph = avg_speed(d, t);
std::cout << kmph.value() << " km/hn";
units::length::mile_t d(140);
units::time::hour_t t(2);
const auto mph = avg_speed(d, t);
std::cout << mph.value() << " mphn";
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Units: Toy example
29
66. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 66/184
template<typename Length, typename Time>
constexpr auto avg_speed(Length d, Time t);
units::length::kilometer_t d(220);
units::time::hour_t t(2);
const auto kmph = avg_speed(d, t);
std::cout << kmph.value() << " km/hn";
units::length::mile_t d(140);
units::time::hour_t t(2);
const auto mph = avg_speed(d, t);
std::cout << mph.value() << " mphn";
meter is a unit, not a quantity!
-- Walter Brown
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Units: Toy example
29
67. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 67/184
• Single header file units.h
• The conversions between units are defined as
ratios at compile time
• UDL support
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Units: Summary
PROS
30
68. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 68/184
• Single header file units.h
• The conversions between units are defined as
ratios at compile time
• UDL support
• Not possible to extend with own base units
• Poor compile-time error messages
• No types that represent dimensions (units only)
• Mixing quantities with units
• Not easily suitable for generic programming
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Units: Summary
PROS CONS
30
69. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 69/184
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
ISSUES WITH CURRENT SOLUTIONS
31
70. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 70/184
constexpr bu::quantity<bu::si::velocity> avg_speed(bu::quantity<bu::si::length> d, bu::quantity<bu::si::time> t)
{ return d * t; }
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
User experience: Compilation: Boost.Units
32
71. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 71/184
constexpr bu::quantity<bu::si::velocity> avg_speed(bu::quantity<bu::si::length> d, bu::quantity<bu::si::time> t)
{ return d * t; }
error: could not convert ‘boost::units::operator*(const boost::units::quantity<Unit1, X>&,
const boost::units::quantity<Unit2, Y>&) [with Unit1 = boost::units::unit<boost::units::list<boost::units::dim
<boost::units::length_base_dimension, boost::units::static_rational<1> >, boost::units::dimensionless_type>,
boost::units::homogeneous_system<boost::units::list<boost::units::si::meter_base_unit,
boost::units::list<boost::units::scaled_base_unit<boost::units::cgs::gram_base_unit, boost::units::scale<10,
boost::units::static_rational<3> > >, boost::units::list<boost::units::si::second_base_unit,
boost::units::list<boost::units::si::ampere_base_unit, boost::units::list<boost::units::si::kelvin_base_unit,
boost::units::list<boost::units::si::mole_base_unit, boost::units::list<boost::units::si::candela_base_unit,
boost::units::list<boost::units::angle::radian_base_unit, boost::units::list<boost::units::angle::steradian_base_unit,
boost::units::dimensionless_type> > > > > > > > > > >; Unit2 = boost::units::unit<boost::units::list<boost::units::dim
<boost::units::time_base_dimension, boost::units::static_rational<1> >, boost::units::dimensionless_type>,
boost::units::homogeneous_system<boost::units::list<boost::units::si::meter_base_unit,
boost::units::list<boost::units::scaled_base_unit<boost::units::cgs::gram_base_unit, boost::units::scale<10,
boost::units::static_rational<3> > >, boost::units::list<boost::units::si::second_base_unit, boost::units::list
<boost::units::si::ampere_base_unit, boost::units::list<boost::units::si::kelvin_base_unit, boost::units::list
<boost::units::si::mole_base_unit, boost::units::list<boost::units::si::candela_base_unit, boost::units::list
<boost::units::angle::radian_base_unit, boost::units::list<boost::units::angle::steradian_base_unit,
boost::units::dimensionless_type> > > > > > > > > > >; X = double; Y = double; typename
boost::units::multiply_typeof_helper<boost::units::quantity<Unit1, X>, boost::units::quantity<Unit2, Y> >::type =
...
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
User experience: Compilation: Boost.Units
GCC-8
32
72. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 72/184
constexpr bu::quantity<bu::si::velocity> avg_speed(bu::quantity<bu::si::length> d, bu::quantity<bu::si::time> t)
{ return d * t; }
...
boost::units::quantity<boost::units::unit<boost::units::list<boost::units::dim<boost::units::length_base_dimension,
boost::units::static_rational<1> >, boost::units::list<boost::units::dim<boost::units::time_base_dimension,
boost::units::static_rational<1> >, boost::units::dimensionless_type> >, boost::units::homogeneous_system
<boost::units::list<boost::units::si::meter_base_unit, boost::units::list<boost::units::scaled_base_unit
<boost::units::cgs::gram_base_unit, boost::units::scale<10, boost::units::static_rational<3> > >,
boost::units::list<boost::units::si::second_base_unit, boost::units::list<boost::units::si::ampere_base_unit,
boost::units::list<boost::units::si::kelvin_base_unit, boost::units::list<boost::units::si::mole_base_unit,
boost::units::list<boost::units::si::candela_base_unit, boost::units::list<boost::units::angle::radian_base_unit,
boost::units::list<boost::units::angle::steradian_base_unit, boost::units::dimensionless_type> > > > > > > > > >,
void>, double>](t)’ from ‘quantity<unit<list<[...],list<dim<[...],static_rational<1>>,[...]>>,[...],[...]>,[...]>’
to ‘quantity<unit<list<[...],list<dim<[...],static_rational<-1>>,[...]>>,[...],[...]>,[...]>’
return d * t;
~~^~~
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
User experience: Compilation: Boost.Units
GCC-8 (CONTINUED)
33
73. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 73/184
constexpr bu::quantity<bu::si::velocity> avg_speed(bu::quantity<bu::si::length> d, bu::quantity<bu::si::time> t)
{ return d * t; }
error: no viable conversion from returned value of type 'quantity<unit<list<[...], list<dim<[...],
static_rational<1, [...]>>, [...]>>, [...]>, [...]>' to function return type 'quantity<unit<list<[...], list<dim<[...],
static_rational<-1, [...]>>, [...]>>, [...]>, [...]>'
return d * t;
^~~~~
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
User experience: Compilation: Boost.Units
CLANG-7
34
74. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 74/184
constexpr bu::quantity<bu::si::velocity> avg_speed(bu::quantity<bu::si::length> d, bu::quantity<bu::si::time> t)
{ return d * t; }
error: no viable conversion from returned value of type 'quantity<unit<list<[...], list<dim<[...],
static_rational<1, [...]>>, [...]>>, [...]>, [...]>' to function return type 'quantity<unit<list<[...], list<dim<[...],
static_rational<-1, [...]>>, [...]>>, [...]>, [...]>'
return d * t;
^~~~~
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
User experience: Compilation: Boost.Units
CLANG-7
Sometimes shorter error message is not necessary better ;-)
34
75. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 75/184
template<typename Length, typename Time>
constexpr auto avg_speed(Length d, Time t) { return d * t; }
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
User experience: Compilation: Units
35
76. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 76/184
template<typename Length, typename Time>
constexpr auto avg_speed(Length d, Time t) { return d * t; }
error: static assertion failed: Units are not compatible.
static_assert(traits::is_convertible_unit<UnitFrom, UnitTo>::value, "Units are not compatible.");
^~~~~~
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
User experience: Compilation: Units
GCC-8
35
77. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 77/184
template<typename Length, typename Time>
constexpr auto avg_speed(Length d, Time t) { return d * t; }
error: static assertion failed: Units are not compatible.
static_assert(traits::is_convertible_unit<UnitFrom, UnitTo>::value, "Units are not compatible.");
^~~~~~
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
User experience: Compilation: Units
GCC-8
static_assert's are o en not the best solution
• do not influence the overload resolution process
• for some compilers do not provide enough context
35
78. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 78/184
template<typename Length, typename Time>
constexpr auto avg_speed(Length d, Time t) { return d * t; }
error: static_assert failed due to requirement 'traits::is_convertible_unit<unit<ratio<3600000, 1>, base_unit<ratio<1, 1>,
ratio<0, 1>, ratio<1, 1>, ratio<0, 1>, ratio<0, 1>, ratio<0, 1>, ratio<0, 1>, ratio<0, 1>, ratio<0, 1> >, ratio<0, 1>,
ratio<0, 1> >, unit<ratio<5, 18>, base_unit<ratio<1, 1>, ratio<0, 1>, ratio<-1, 1>, ratio<0, 1>, ratio<0, 1>, ratio<0, 1>,
ratio<0, 1>, ratio<0, 1>, ratio<0, 1> >, ratio<0, 1>, ratio<0, 1> > >::value' "Units are not compatible."
static_assert(traits::is_convertible_unit<UnitFrom, UnitTo>::value, "Units are not compatible.");
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
User experience: Compilation: Units
CLANG-7
36
79. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 79/184
• For most template metaprogramming libraries compile-time errors are rare
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
A need to modernize our toolbox
37
80. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 80/184
• For most template metaprogramming libraries compile-time errors are rare
• It is expected that engineers working with physical units library will experience compile-time errors
very o en
– generating compile-time errors for invalid calculation is the main reason to create such a library
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
A need to modernize our toolbox
37
81. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 81/184
• For most template metaprogramming libraries compile-time errors are rare
• It is expected that engineers working with physical units library will experience compile-time errors
very o en
– generating compile-time errors for invalid calculation is the main reason to create such a library
In case of the physical units library we have to rethink the way we
do template metaprogramming!
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
A need to modernize our toolbox
37
82. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 82/184
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
User experience: Debugging: Boost.Units
38
83. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 83/184
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
User experience: Debugging: Boost.Units
38
84. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 84/184
Breakpoint 1, avg_speed<boost::units::heterogeneous_system<boost::units::heterogeneous_system_impl
<boost::units::list<boost::units::heterogeneous_system_dim<boost::units::si::meter_base_unit, boost::units::static_rational<1> >,
boost::units::dimensionless_type>, boost::units::list<boost::units::dim<boost::units::length_base_dimension,
boost::units::static_rational<1> >, boost::units::dimensionless_type>, boost::units::list<boost::units::scale_list_dim
<boost::units::scale<10, boost::units::static_rational<3> > >, boost::units::dimensionless_type> > >,
boost::units::heterogeneous_system<boost::units::heterogeneous_system_impl<boost::units::list
<boost::units::heterogeneous_system_dim<boost::units::scaled_base_unit<boost::units::si::second_base_unit,
boost::units::scale<60, boost::units::static_rational<2> > >, boost::units::static_rational<1> >,
boost::units::dimensionless_type>, boost::units::list<boost::units::dim<boost::units::time_base_dimension,
boost::units::static_rational<1> >, boost::units::dimensionless_type>, boost::units::dimensionless_type> > > (d=..., t=...) at
velocity_2.cpp:39
39 return d / t;
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
User experience: Debugging: Boost.Units
39
85. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 85/184
(gdb) ptype d
type = class boost::units::quantity<boost::units::unit<boost::units::list<boost::units::dim<boost::units::length_base_dimension,
boost::units::static_rational<1, 1> >, boost::units::dimensionless_type>, boost::units::heterogeneous_system
<boost::units::heterogeneous_system_impl<boost::units::list<boost::units::heterogeneous_system_dim
<boost::units::si::meter_base_unit, boost::units::static_rational<1, 1> >, boost::units::dimensionless_type>,
boost::units::list<boost::units::dim<boost::units::length_base_dimension, boost::units::static_rational<1, 1> >,
boost::units::dimensionless_type>, boost::units::list<boost::units::scale_list_dim<boost::units::scale<10, static_rational<3> > >,
boost::units::dimensionless_type> > >, void>, double> [with Unit = boost::units::unit<boost::units::list<boost::units::dim
<boost::units::length_base_dimension, boost::units::static_rational<1, 1> >, boost::units::dimensionless_type>,
boost::units::heterogeneous_system<boost::units::heterogeneous_system_impl<boost::units::list
<boost::units::heterogeneous_system_dim<boost::units::si::meter_base_unit, boost::units::static_rational<1, 1> >,
boost::units::dimensionless_type>, boost::units::list<boost::units::dim<boost::units::length_base_dimension,
boost::units::static_rational<1, 1> >, boost::units::dimensionless_type>, boost::units::list<boost::units::scale_list_dim
<boost::units::scale<10, static_rational<3> > >, boost::units::dimensionless_type> > >, void>, Y = double] {
...
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
User experience: Debugging: Boost.Units
40
86. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 86/184
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
User experience: Debugging: Units
41
87. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 87/184
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
User experience: Debugging: Units
41
88. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 88/184
Breakpoint 1, avg_speed<units::unit_t<units::unit<std::ratio<1000, 1>, units::unit<std::ratio<1>,
units::base_unit<std::ratio<1> > >, std::ratio<0, 1>, std::ratio<0, 1> > >, units::unit_t<units::unit<std::ratio<60>,
units::unit<std::ratio<60>, units::unit<std::ratio<1>, units::base_unit<std::ratio<0, 1>, std::ratio<0, 1>,
std::ratio<1> > > > > > >
(d=..., t=...) at velocity.cpp:28
28 const auto v = d / t;
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
User experience: Debugging: Units
42
89. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 89/184
(gdb) ptype d
type = class units::unit_t<units::unit<std::ratio<1000, 1>, units::unit<std::ratio<1, 1>, units::base_unit<std::ratio<1, 1>,
std::ratio<0, 1>, std::ratio<0, 1>, std::ratio<0, 1>, std::ratio<0, 1>, std::ratio<0, 1>, std::ratio<0, 1>, std::ratio<0, 1>,
std::ratio<0, 1> >, std::ratio<0, 1>, std::ratio<0, 1> >, std::ratio<0, 1>, std::ratio<0, 1> >, double, units::linear_scale>
[with Units = units::unit<std::ratio<1000, 1>, units::unit<std::ratio<1, 1>, units::base_unit<std::ratio<1, 1>, std::ratio<0, 1>,
std::ratio<0, 1>, std::ratio<0, 1>, std::ratio<0, 1>, std::ratio<0, 1>, std::ratio<0, 1>, std::ratio<0, 1>, std::ratio<0, 1> >,
std::ratio<0, 1>, std::ratio<0, 1> >, std::ratio<0, 1>, std::ratio<0, 1> >, T = double] : public units::linear_scale<T>,
private units::detail::_unit_t {
...
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
User experience: Debugging: Units
43
90. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 90/184
BOOST_UNITS_DEFINE_CONVERSION_FACTOR(foot_base_unit, meter_base_unit, double, 0.3048);
BOOST_UNITS_DEFINE_CONVERSION_OFFSET(celsius_base_unit, fahrenheit_base_unit, double, 32.0);
BOOST_UNITS_DEFAULT_CONVERSION(my_unit_tag, SI::force);
BOOST_UNITS_DEFINE_CONVERSION_FACTOR_TEMPLATE((long N1)(long N2),
currency_base_unit<N1>,
currency_base_unit<N2>,
double, get_conversion_factor(N1, N2));
and more...
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Macros omnipresence: Boost.Units
44
92. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 92/184
• Adding derived dimensions is pretty easy in all the libraries
• Adding base dimensions is hard or nearly impossible
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Extensibility
46
93. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 93/184
• Adding derived dimensions is pretty easy in all the libraries
• Adding base dimensions is hard or nearly impossible
struct length_base_dimension : base_dimension<length_base_dimension, 1> {};
struct mass_base_dimension : base_dimension<mass_base_dimension, 2> {};
struct time_base_dimension : base_dimension<time_base_dimension, 3> {};
• Order is completely arbitrary as long as each tag has a unique enumerable value
• Non-unique ordinals are flagged as errors at compile-time
• Negative ordinals are reserved for use by the library
• Two independent libraries can easily choose the same ordinal (i.e. 1)
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Extensibility
BOOST.UNITS
46
94. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 94/184
• Adding derived dimensions is pretty easy in all the libraries
• Adding base dimensions is hard or nearly impossible
template<class Meter = detail::meter_ratio<0>,
class Kilogram = std::ratio<0>,
class Second = std::ratio<0>,
class Radian = std::ratio<0>,
class Ampere = std::ratio<0>,
class Kelvin = std::ratio<0>,
class Mole = std::ratio<0>,
class Candela = std::ratio<0>,
class Byte = std::ratio<0>>
struct base_unit;
• Requires refactoring the engine, all existing predefined and users' unit types
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Extensibility
UNITS
47
95. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 95/184
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
MY UNITS LIBRARY (WIP!!!)
H T T P S : / / G I T H U B . C O M / M P U S Z / U N I T S
48
96. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 96/184
• The best possible user experience
– compiler errors
– debugging
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Requirements
49
97. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 97/184
• The best possible user experience
– compiler errors
– debugging
• Safety and performance
– strong types
– template metaprogramming
– constexpr all the things
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Requirements
49
98. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 98/184
• The best possible user experience
– compiler errors
– debugging
• Safety and performance
– strong types
– template metaprogramming
– constexpr all the things
• No macros in the user interface
• No external dependencies
• Easy extensibility
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Requirements
49
99. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 99/184
• The best possible user experience
– compiler errors
– debugging
• Safety and performance
– strong types
– template metaprogramming
– constexpr all the things
• No macros in the user interface
• No external dependencies
• Easy extensibility
• Possibility to be standardized as a freestanding part of the C++ Standard Library
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Requirements
49
100. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 100/184
• units::dimension - a type-list-like type that stores an ordered list of exponents of one or more base
dimensions
template<typename... Exponents>
struct dimension;
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Dimensions
50
101. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 101/184
• units::dimension - a type-list-like type that stores an ordered list of exponents of one or more base
dimensions
template<typename... Exponents>
struct dimension;
• units::exp - a base dimension and its exponent in a derived dimension
template<typename BaseDimension, int Value>
struct exp {
using dimension = BaseDimension;
static constexpr int value = Value;
};
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Dimensions
50
102. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 102/184
• BaseDimension is a unique sortable compile-time value
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Dimensions
51
103. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 103/184
• BaseDimension is a unique sortable compile-time value
template<int UniqueValue>
using dim_id = std::integral_constant<int, UniqueValue>;
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Dimensions
51
104. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 104/184
• BaseDimension is a unique sortable compile-time value
template<int UniqueValue>
using dim_id = std::integral_constant<int, UniqueValue>;
struct base_dim_length : dim_id<0> {};
struct base_dim_mass : dim_id<1> {};
struct base_dim_time : dim_id<2> {};
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Dimensions
EXAMPLE
51
105. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 105/184
• BaseDimension is a unique sortable compile-time value
template<int UniqueValue>
using dim_id = std::integral_constant<int, UniqueValue>;
struct base_dim_length : dim_id<0> {};
struct base_dim_mass : dim_id<1> {};
struct base_dim_time : dim_id<2> {};
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Dimensions
EXAMPLE
The same problem with extensibility as with Boost.Units. If two users will
select the same ID for their types than we have problems
51
106. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 106/184
• Allow non-union class types to appear in non-type template parameters
• Require that types used as such, have strong structural equality
– a type T is having strong structural equality if each subobject recursively has defaulted == and none
of the subobjects are floating point types
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
P0732 P1185 Class Types in Non-Type Template Parameters
52
107. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 107/184
• Allow non-union class types to appear in non-type template parameters
• Require that types used as such, have strong structural equality
– a type T is having strong structural equality if each subobject recursively has defaulted == and none
of the subobjects are floating point types
template<fixed_string Id>
class entity { /* ... */ };
entity<"hello"> e;
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
P0732 P1185 Class Types in Non-Type Template Parameters
52
108. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 108/184
• base_dimension can be either directly fixed_string or a type that will include additional information
(i.e. user's namespace name)
using base_dimension = fixed_string;
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
C++20 Exponent and Base Dimension
53
109. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 109/184
• base_dimension can be either directly fixed_string or a type that will include additional information
(i.e. user's namespace name)
using base_dimension = fixed_string;
inline constexpr base_dimension base_dim_length("length");
inline constexpr base_dimension base_dim_time("time");
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
C++20 Exponent and Base Dimension
EXAMPLE
53
110. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 110/184
• base_dimension can be either directly fixed_string or a type that will include additional information
(i.e. user's namespace name)
using base_dimension = fixed_string;
inline constexpr base_dimension base_dim_length("length");
inline constexpr base_dimension base_dim_time("time");
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
C++20 Exponent and Base Dimension
EXAMPLE
Much easier to extend the library with new base dimension without identifier
collisions between vendors
53
111. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 111/184
• We can express velocity in the following way
dimension<exp<base_dim_length, 1>, exp<base_dim_time, -1>>
– improves user experience
– as short as possible template instantiations
– easy to understand by every engineer
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Dimensions
54
112. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 112/184
• We can express velocity in the following way
dimension<exp<base_dim_length, 1>, exp<base_dim_time, -1>>
– improves user experience
– as short as possible template instantiations
– easy to understand by every engineer
• The same type expected for both operations
constexpr auto v1 = 1_m / 1_s;
constexpr auto v2 = 2 / 2_s * 1_m;
static_assert(std::is_same<decltype(v1), decltype(v2)>);
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Dimensions
PROBLEM
54
113. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 113/184
template<typename... Exponents>
struct make_dimension {
using type = /* unspecified */;
};
template<typename... Exponents>
using make_dimension_t = make_dimension<Exponents...>::type;
• Provides unique ordering for contained base dimensions
• Aggregates two arguments of the same base dimension but di erent exponents
• Eliminates two arguments of the same base dimension and with opposite equal exponents
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Dimensions: make_dimension factory helper
55
114. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 114/184
template<typename... Exponents>
struct make_dimension {
using type = /* unspecified */;
};
template<typename... Exponents>
using make_dimension_t = make_dimension<Exponents...>::type;
• Provides unique ordering for contained base dimensions
• Aggregates two arguments of the same base dimension but di erent exponents
• Eliminates two arguments of the same base dimension and with opposite equal exponents
• To form a velocity
make_dimension_t<exp<base_dim_length, 1>, exp<base_dim_time, -1>>
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Dimensions: make_dimension factory helper
EXAMPLE
55
115. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 115/184
• unit - the unit of a specific physical dimension
template<typename Dimension, typename Ratio = std::ratio<1>>
struct unit {
using dimension = Dimension;
using ratio = Ratio;
};
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Units
56
116. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 116/184
• unit - the unit of a specific physical dimension
template<typename Dimension, typename Ratio = std::ratio<1>>
struct unit {
using dimension = Dimension;
using ratio = Ratio;
};
To express meter
unit<dimension_length>
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Units
EXAMPLE
56
117. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 117/184
• quantity - the amount of a specific dimension expressed in a specific unit of that dimension
template<typename Dimension, typename Unit, typename Rep>
class quantity;
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Quantities
57
118. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 118/184
• quantity - the amount of a specific dimension expressed in a specific unit of that dimension
template<typename Dimension, typename Unit, typename Rep>
class quantity;
• Interface similar to std::chrono::duration + additional member functions
– multiplication of 2 quantities with di erent dimensions
1_kmph * 1_h == 1_km
– division of 2 quantities of di erent dimensions
1_km / 1_h == 1_kmph
– division of a scalar with a quantity
1 / 1_s == 1_Hz
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Quantities
57
119. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 119/184
• quantity - the amount of a specific dimension expressed in a specific unit of that dimension
template<typename Dimension, typename Unit, typename Rep>
class quantity;
template<typename Unit = meter_per_second, typename Rep = double>
using velocity = quantity<dimension_velocity, Unit, Rep>;
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Quantities
EXAMPLE
58
120. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 120/184
What is the quantity? An absolute or a relative value?
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Important design question
59
121. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 121/184
What is the quantity? An absolute or a relative value?
• For most dimensions only relative values have sense
– Where is absolute 123 meters?
– If I am sitting in a moving train is my velocity == 0?
– Is my velocity == 0 when the train stops?
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Important design question
59
122. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 122/184
What is the quantity? An absolute or a relative value?
• For most dimensions only relative values have sense
– Where is absolute 123 meters?
– If I am sitting in a moving train is my velocity == 0?
– Is my velocity == 0 when the train stops?
• For some dimensions absolute values are really needed
– temperature
– time
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Important design question
59
123. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 123/184
1 Generic programming
2 Compile-time errors
3 Debugging
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Struggling with the user experience
60
124. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 124/184
• Is it really a velocity dimension?
template<typename LengthSystem, typename Rep1, typename TimeSystem, typename Rep2>
constexpr auto avg_speed(bu::quantity<bu::unit<bu::length_dimension, LengthSystem>, Rep1> d,
bu::quantity<bu::unit<bu::time_dimension, TimeSystem>, Rep2> t)
{ return d / t; }
template<typename Length, typename Time>
constexpr auto avg_speed(Length d, Time t)
{
static_assert(units::traits::is_length_unit<Length>::value);
static_assert(units::traits::is_time_unit<Time>::value);
const auto v = d / t;
static_assert(units::traits::is_velocity_unit<decltype(v)>::value);
return v;
}
• Not possible to define template arguments that will provide proper overload resolution
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Do you remember that?
BOOST.UNITS
UNITS
61
125. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 125/184
#include <boost/units/is_quantity_of_dimension.hpp>
template<typename Quantity, typename Dimension>
concept QuantityOf = bu::is_quantity_of_dimension<Quantity, Dimension>::value;
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
C++ Concepts to the rescue
BOOST.UNITS
62
126. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 126/184
#include <boost/units/is_quantity_of_dimension.hpp>
template<typename Quantity, typename Dimension>
concept QuantityOf = bu::is_quantity_of_dimension<Quantity, Dimension>::value;
template<typename Quantity>
concept Length = QuantityOf<Quantity, bu::length_dimension>;
template<typename Quantity>
concept Time = QuantityOf<Quantity, bu::time_dimension>;
template<typename Quantity>
concept Velocity = QuantityOf<Quantity, bu::velocity_dimension>;
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
C++ Concepts to the rescue
BOOST.UNITS
62
127. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 127/184
#include <boost/units/is_quantity_of_dimension.hpp>
template<typename Quantity, typename Dimension>
concept QuantityOf = bu::is_quantity_of_dimension<Quantity, Dimension>::value;
template<typename Quantity>
concept Length = QuantityOf<Quantity, bu::length_dimension>;
template<typename Quantity>
concept Time = QuantityOf<Quantity, bu::time_dimension>;
template<typename Quantity>
concept Velocity = QuantityOf<Quantity, bu::velocity_dimension>;
constexpr Velocity auto avg_speed(Length auto d, Time auto t) { return d / t; }
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
C++ Concepts to the rescue
BOOST.UNITS
62
128. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 128/184
template<typename T>
concept Length = units::traits::is_length_unit<T>::value;
template<typename T>
concept Time = units::traits::is_time_unit<T>::value;
template<typename T>
concept Velocity = units::traits::is_velocity_unit<T>::value;
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
C++ Concepts to the rescue
UNITS
63
129. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 129/184
template<typename T>
concept Length = units::traits::is_length_unit<T>::value;
template<typename T>
concept Time = units::traits::is_time_unit<T>::value;
template<typename T>
concept Velocity = units::traits::is_velocity_unit<T>::value;
constexpr Velocity auto avg_speed(Length auto d, Time auto t) { return d / t; }
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
C++ Concepts to the rescue
UNITS
63
130. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 130/184
template<typename T>
concept Length = units::traits::is_length_unit<T>::value;
template<typename T>
concept Time = units::traits::is_time_unit<T>::value;
template<typename T>
concept Velocity = units::traits::is_velocity_unit<T>::value;
constexpr Velocity auto avg_speed(Length auto d, Time auto t) { return d / t; }
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
C++ Concepts to the rescue
UNITS
Concepts can also be used in places where regular template argument
deduction does not work (i.e. return types, class template parameters, etc).
63
131. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 131/184
All template types are heavily embraced with concepts
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
I lied a bit ;-)
64
132. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 132/184
• TypeList
• Scalar
• Ratio
• Exponent
• Dimension
• Unit
• Quantity
All template types are heavily embraced with concepts
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
I lied a bit ;-)
UNITS ENGINE CONCEPTS
64
133. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 133/184
• TypeList
• Scalar
• Ratio
• Exponent
• Dimension
• Unit
• Quantity
• Length
• Time
• Frequency
• Velocity
• ...
template<typename T>
concept Velocity = Quantity<T> &&
std::Same<typename T::dimension, dimension_velocity>;
All template types are heavily embraced with concepts
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
I lied a bit ;-)
UNITS ENGINE CONCEPTS PREDEFINED QUANTITIES CONCEPTS
64
134. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 134/184
• Velocity is one of the simplest derived dimensions one can imagine
using velocity = make_dimension_t<exp<base_dim_length, 1>, exp<base_dim_time, -1>>;
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Type aliases are great (but not for users)
65
135. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 135/184
• Velocity is one of the simplest derived dimensions one can imagine
using velocity = make_dimension_t<exp<base_dim_length, 1>, exp<base_dim_time, -1>>;
• Type aliases names are lost quickly during compilation process
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Type aliases are great (but not for users)
65
136. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 136/184
• Velocity is one of the simplest derived dimensions one can imagine
using velocity = make_dimension_t<exp<base_dim_length, 1>, exp<base_dim_time, -1>>;
• Type aliases names are lost quickly during compilation process
• As a result user gets huge types in error messages
[with D = units::quantity<units::dimension<units::exp<units::base_dim_length, 1>, units::exp<units::base_dim_time, -1> >,
units::unit<units::dimension<units::exp<units::base_dim_length, 1>, units::exp<units::base_dim_time, -1> >,
std::ratio<1000, 3600> >, long long int>]
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Type aliases are great (but not for users)
65
137. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 137/184
• Velocity is one of the simplest derived dimensions one can imagine
using velocity = make_dimension_t<exp<base_dim_length, 1>, exp<base_dim_time, -1>>;
• Type aliases names are lost quickly during compilation process
• As a result user gets huge types in error messages
[with D = units::quantity<units::dimension<units::exp<units::base_dim_length, 1>, units::exp<units::base_dim_time, -1> >,
units::unit<units::dimension<units::exp<units::base_dim_length, 1>, units::exp<units::base_dim_time, -1> >,
std::ratio<1000, 3600> >, long long int>]
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Type aliases are great (but not for users)
It is a pity that we still do not have strong typedef's in the C++ language :-(
65
138. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 138/184
struct dimension_velocity : make_dimension_t<exp<base_dim_length, 1>,
exp<base_dim_time, -1>> {};
• We get strong types that do not vanish during compilation process
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Inheritance to the rescue
66
139. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 139/184
Velocity auto v = 10_m / 2_s;
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Upcasting problem
67
140. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 140/184
Velocity auto v = 10_m / 2_s;
template<Dimension D1, Unit U1, Scalar Rep1, Dimension D2, Unit U2, Scalar Rep2>
constexpr Quantity operator/(const quantity<D1, U1, Rep1>& lhs,
const quantity<D2, U2, Rep2>& rhs);
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Upcasting problem
67
141. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 141/184
Velocity auto v = 10_m / 2_s;
template<Dimension D1, Unit U1, Scalar Rep1, Dimension D2, Unit U2, Scalar Rep2>
constexpr Quantity operator/(const quantity<D1, U1, Rep1>& lhs,
const quantity<D2, U2, Rep2>& rhs);
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Upcasting problem
How to form dimension_velocity child class from division of
dimension_length by dimension_time?
67
142. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 142/184
template<typename T>
struct type_identity { using type = T; };
template<typename T>
using type_identity_t = type_identity<T>::type;
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
P0887 The identity metafunction
68
143. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 143/184
template<typename BaseType>
struct upcast_base {
using base_type = BaseType;
};
template<Exponent... Es>
struct dimension : upcast_base<dimension<Es...>> {};
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Upcasting facility
BASE CLASS
69
144. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 144/184
template<typename BaseType>
struct upcast_base {
using base_type = BaseType;
};
template<Exponent... Es>
struct dimension : upcast_base<dimension<Es...>> {};
template<typename T>
concept Upcastable =
requires {
typename T::base_type;
} &&
std::DerivedFrom<T, upcast_base<typename T::base_type>>;
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Upcasting facility
BASE CLASS
UPCASTABLE
69
145. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 145/184
template<Upcastable T>
using upcast_from = T::base_type;
template<Upcastable T>
using upcast_to = std::type_identity<T>;
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Upcasting facility
HELPER ALIASES
70
146. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 146/184
template<Upcastable T>
using upcast_from = T::base_type;
template<Upcastable T>
using upcast_to = std::type_identity<T>;
template<Upcastable T>
struct upcasting_traits : upcast_to<T> {};
template<Upcastable T>
using upcasting_traits_t = upcasting_traits<T>::type;
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Upcasting facility
HELPER ALIASES
UPCASTING TRAITS
70
147. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 147/184
template<Exponent... Es>
struct dimension : upcast_base<dimension<Es...>> {};
struct dimension_velocity : make_dimension_t<exp<base_dim_length, 1>,
exp<base_dim_time, -1>> {};
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Upcasting dimension
71
148. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 148/184
template<Exponent... Es>
struct dimension : upcast_base<dimension<Es...>> {};
struct dimension_velocity : make_dimension_t<exp<base_dim_length, 1>,
exp<base_dim_time, -1>> {};
template<>
struct upcasting_traits<upcast_from<dimension_velocity>> : upcast_to<dimension_velocity> {};
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Upcasting dimension
71
149. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 149/184
template<Exponent... Es>
struct dimension : upcast_base<dimension<Es...>> {};
struct dimension_velocity : make_dimension_t<exp<base_dim_length, 1>,
exp<base_dim_time, -1>> {};
template<>
struct upcasting_traits<upcast_from<dimension_velocity>> : upcast_to<dimension_velocity> {};
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Upcasting dimension
Help needed: How to automate the last line?
71
150. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 150/184
[with D = units::quantity<units::dimension<units::exp<units::base_dim_length, 1>, units::exp<units::base_dim_time, -1> >,
units::unit<units::dimension<units::exp<units::base_dim_length, 1>, units::exp<units::base_dim_time, -1> >,
std::ratio<1000, 3600> >, long long int>]
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Upcasting facility
BEFORE
72
151. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 151/184
[with D = units::quantity<units::dimension<units::exp<units::base_dim_length, 1>, units::exp<units::base_dim_time, -1> >,
units::unit<units::dimension<units::exp<units::base_dim_length, 1>, units::exp<units::base_dim_time, -1> >,
std::ratio<1000, 3600> >, long long int>]
[with D = units::quantity<units::dimension_velocity, units::kilometer_per_hour, long long int>
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Upcasting facility
BEFORE
AFTER
72
152. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 152/184
template<Dimension D, Unit U, Scalar Rep>
requires std::Same<D, typename U::dimension>
class quantity {
public:
template<Dimension D, Unit U1, Scalar Rep1, Unit U2, Scalar Rep2>
[[nodiscard]] constexpr Scalar operator/(const quantity<D, U1, Rep1>& lhs,
const quantity<D, U2, Rep2>& rhs)
{
Expects(rhs != quantity<D, U2, Rep2>(0));
// ...
}
};
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Contracts
73
153. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 153/184
template<Dimension D, Unit U, Scalar Rep>
requires std::Same<D, typename U::dimension>
class quantity {
public:
template<Dimension D, Unit U1, Scalar Rep1, Unit U2, Scalar Rep2>
[[nodiscard]] constexpr Scalar operator/(const quantity<D, U1, Rep1>& lhs,
const quantity<D, U2, Rep2>& rhs)
{
Expects(rhs != quantity<D, U2, Rep2>(0));
// ...
}
};
error: macro "Expects" passed 3 arguments, but takes just 1
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Contracts
73
154. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 154/184
template<Dimension D, Unit U, Scalar Rep>
requires std::Same<D, typename U::dimension>
class quantity {
public:
template<Dimension D, Unit U1, Scalar Rep1, Unit U2, Scalar Rep2>
[[nodiscard]] constexpr Scalar operator/(const quantity<D, U1, Rep1>& lhs,
const quantity<D, U2, Rep2>& rhs)
{
using rhs_type = quantity<D, U2, Rep2>;
Expects(rhs != rhs_type(0));
// ...
}
};
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Contracts
74
155. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 155/184
template<Dimension D, Unit U, Scalar Rep>
requires std::Same<D, typename U::dimension>
class quantity {
public:
template<Dimension D, Unit U1, Scalar Rep1, Unit U2, Scalar Rep2>
[[nodiscard]] constexpr Scalar operator/(const quantity<D, U1, Rep1>& lhs,
const quantity<D, U2, Rep2>& rhs)
{
Expects(rhs != std::remove_cvref_t<decltype(rhs)>(0));
// ...
}
};
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Contracts
75
156. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 156/184
template<Dimension D, Unit U, Scalar Rep>
requires std::Same<D, typename U::dimension>
class quantity {
public:
template<Dimension D, Unit U1, Scalar Rep1, Unit U2, Scalar Rep2>
[[nodiscard]] constexpr Scalar operator/(const quantity<D, U1, Rep1>& lhs,
const quantity<D, U2, Rep2>& rhs)
{
Expects(rhs != std::remove_cvref_t<decltype(rhs)>(0));
// ...
}
};
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Contracts
Still not the best solution:
• usage of a macro in a header file (possible ODR issue)
• not a part of a function signature
75
157. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 157/184
template<Dimension D, Unit U, Scalar Rep>
requires std::Same<D, typename U::dimension>
class quantity {
public:
template<Dimension D, Unit U1, Scalar Rep1, Unit U2, Scalar Rep2>
[[nodiscard]] constexpr Scalar operator/(const quantity<D, U1, Rep1>& lhs,
const quantity<D, U2, Rep2>& rhs) [[expects: rhs != quantity<D, U2, Rep2>(0)]]
{
// ...
}
};
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
C++20 Contracts
76
158. 25.05.2019 Implementing a Physical Units Library for C++
file:///C:/repos/cpptrainings_refactor/build/out/implementing_units/implementing_units.html#1 158/184
constexpr units::Velocity auto avg_speed(units::Length auto d, units::Time auto t)
{
return d / t;
}
C++ CoreHard Spring 2019 | Implementing a Physical Units Library for C++
Toy example
77