C++ Reactive Programming
eBook - ePub

C++ Reactive Programming

Design concurrent and asynchronous applications using the RxCpp library and Modern C++17

Praseed Pai, Peter Abraham

Condividi libro
  1. 328 pagine
  2. English
  3. ePUB (disponibile sull'app)
  4. Disponibile su iOS e Android
eBook - ePub

C++ Reactive Programming

Design concurrent and asynchronous applications using the RxCpp library and Modern C++17

Praseed Pai, Peter Abraham

Dettagli del libro
Anteprima del libro
Indice dei contenuti
Citazioni

Informazioni sul libro

Learn how to implement the reactive programming paradigm with C++ and build asynchronous and concurrent applications

Key Features

  • Efficiently exploit concurrency and parallelism in your programs
  • Use the Functional Reactive programming model to structure programs
  • Understand reactive GUI programming to make your own applications using Qt

Book Description

Reactive programming is an effective way to build highly responsive applications with an easy-to-maintain code base. This book covers the essential functional reactive concepts that will help you build highly concurrent, event-driven, and asynchronous applications in a simpler and less error-prone way.

C++ Reactive Programming begins with a discussion on how event processing was undertaken by different programming systems earlier. After a brisk introduction to modern C++ (C++17), you'll be taken through language-level concurrency and the lock-free programming model to set the stage for our foray into the Functional Programming model. Following this, you'll be introduced to RxCpp and its programming model. You'll be able to gain deep insights into the RxCpp library, which facilitates reactive programming. You'll learn how to deal with reactive programming using Qt/C++ (for the desktop) and C++ microservices for the Web.

By the end of the book, you will be well versed with advanced reactive programming concepts in modern C++ (C++17).

What you will learn

  • Understand language-level concurrency in C++
  • Explore advanced C++ programming for the FRP
  • Uncover the RxCpp library and its programming model
  • Mix the FP and OOP constructs in C++ 17 to write well-structured programs
  • Master reactive microservices in C++
  • Create custom operators for RxCpp
  • Learn advanced stream processing and error handling

Who this book is for

If you're a C++ developer interested in using reactive programming to build asynchronous and concurrent applications, you'll find this book extremely useful. This book doesn't assume any previous knowledge of reactive programming.

Domande frequenti

Come faccio ad annullare l'abbonamento?
È semplicissimo: basta accedere alla sezione Account nelle Impostazioni e cliccare su "Annulla abbonamento". Dopo la cancellazione, l'abbonamento rimarrà attivo per il periodo rimanente già pagato. Per maggiori informazioni, clicca qui
È possibile scaricare libri? Se sì, come?
Al momento è possibile scaricare tramite l'app tutti i nostri libri ePub mobile-friendly. Anche la maggior parte dei nostri PDF è scaricabile e stiamo lavorando per rendere disponibile quanto prima il download di tutti gli altri file. Per maggiori informazioni, clicca qui
Che differenza c'è tra i piani?
Entrambi i piani ti danno accesso illimitato alla libreria e a tutte le funzionalità di Perlego. Le uniche differenze sono il prezzo e il periodo di abbonamento: con il piano annuale risparmierai circa il 30% rispetto a 12 rate con quello mensile.
Cos'è Perlego?
Perlego è un servizio di abbonamento a testi accademici, che ti permette di accedere a un'intera libreria online a un prezzo inferiore rispetto a quello che pagheresti per acquistare un singolo libro al mese. Con oltre 1 milione di testi suddivisi in più di 1.000 categorie, troverai sicuramente ciò che fa per te! Per maggiori informazioni, clicca qui.
Perlego supporta la sintesi vocale?
Cerca l'icona Sintesi vocale nel prossimo libro che leggerai per verificare se è possibile riprodurre l'audio. Questo strumento permette di leggere il testo a voce alta, evidenziandolo man mano che la lettura procede. Puoi aumentare o diminuire la velocità della sintesi vocale, oppure sospendere la riproduzione. Per maggiori informazioni, clicca qui.
C++ Reactive Programming è disponibile online in formato PDF/ePub?
Sì, puoi accedere a C++ Reactive Programming di Praseed Pai, Peter Abraham in formato PDF e/o ePub, così come ad altri libri molto apprezzati nelle sezioni relative a Computer Science e Programming in C++. Scopri oltre 1 milione di libri disponibili nel nostro catalogo.

Informazioni

Anno
2018
ISBN
9781788624244
Edizione
1

A Tour of Modern C++ and its Key Idioms

The classic C++ programming language was standardized in 1998 and it was followed by a small revision (mostly corrections) in 2003. To support advanced abstractions, developers relied on the Boost (http://www.boost.org) library and other public domain libraries. Thanks to the next wave of standardization, the language (from C++ 11 onward) was enhanced, and now developers can encode most widely used abstractions (supported by other languages) without relying on external libraries. Even threads and file-system interfaces, which came squarely under the aegis of libraries, are now part of the standard language. Modern C++ (which stands for C++ versions 11/14/17 ) contains superb additions to the language and its libraries, that make C++ the de-facto choice for writing industrial strength production software. The features covered in this chapter are the minimum set of features that a programmer has to understand to work with Reactive Programming constructs in general and RxCpp in particular. The primary objective of this chapter is to cover the most important additions to the language which makes implementing Reactive Programming constructs easier without resorting to esoteric language techniques. Constructs such as Lambda functions, automatic type inference, rvalue references, move semantics, and language level concurrency are some of the constructs which the authors of this book feel that every C++ programmer should know. In this chapter, we will cover the following topics:
  • Key concerns for C++ programming language design
  • Some enhancements to C++ for writing better code
  • Better memory management through rvalue references and move semantics
  • Better object lifetime management using an enhanced set of smart pointers
  • Behavioral parameterization using Lambda functions and expressions
  • Function Wrappers (the std::function type)
  • Miscellaneous features
  • Writing Iterators and Observers (to put everything together)

The key concerns of the C++ programming language

As far as developers are concerned, the three key concerns that C++ programming language designers keep in mind were (and still are) as follows:
  • Zero Cost Abstraction - No performance penalty for higher level abstraction
  • Expressivity - A user defined type (UDT) or class should be as expressive as built-in types
  • Substitutability - A UDT can be substituted wherever built-in-types are expected (as in generic data structures and algorithms)
We will discuss these briefly.

Zero cost abstraction

The C++ programming language has always helped developers to write code that exploits the microprocessor (on which generated code runs) and also raise the level of abstraction when it matters. While raising the abstraction, the designers of the language have always tried to minimize (almost eliminate) their performance overhead. This is called Zero Cost Abstraction or Zero Overhead Cost Abstraction. The only notable penalty you pay is the cost of indirect calls (through function pointers) while dispatching virtual functions. Despite adding tons of features to the language, the designers have maintained the "Zero Cost Abstraction" guarantee implied by the language from its inception.

Expressivity

C++ helps a developer to write user defined types or classes that can be as expressive as the built-in types of the programming languages. This enables one to write a arbitrary-precision arithmetic class (monikered as BigInteger/BigFloat in some languages), which contains all the features of a double or float. For the sake of explanation, we have defined a SmartFloat class that wraps IEEE double precision floating point numbers and most of the operators available to the double data type is overloaded. The following code snippets show that one can write types that mimic the semantics of built-in types such as int, float, or double:
//---- SmartFloat.cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class SmartFloat {
double _value; // underlying store
public:
SmartFloat(double value) : _value(value) {}
SmartFloat() : _value(0) {}
SmartFloat( const SmartFloat& other ) { _value = other._value; }
SmartFloat& operator = ( const SmartFloat& other ) {
if ( this != &other ) { _value = other._value;}
return *this;
}
SmartFloat& operator = (double value )
{ _value = value; return *this;}
~SmartFloat(){ }
The SmartFloat class wraps a double value and has defined some constructors and assignment operators to initialize instances properly. In the following snippet, we will define some operators that help to increment the value. Both the prefix and postfix variants of operators are defined:
 SmartFloat& operator ++ () { _value++; return *this; }
SmartFloat operator ++ (int) { // postfix operator
SmartFloat nu(*this); ++_value; return nu;
}
SmartFloat& operator -- () { _value--; return *this; }
SmartFloat operator -- (int) {
SmartFloat nu(*this); --_value; return nu;
}
The preceding code snippets implement increment operators (both prefix and postfix) and are meant for demonstration purposes only. In a real-world class, we will check for floating point overflow and underflow to make the code more robust. The whole purpose of wrapping a type is to write robust code!
 SmartFloat& operator += ( double x ) { _value += x; return *this;}
SmartFloat& operator -= ( double x ) { _value -= x;return *this; }
SmartFloat& operator *= ( double x ) { _value *= x; return *this;}
SmartFloat& operator /= ( double x ) { _value /= x; return *this;}
The preceding code snippets implement C++ style assignment operators and once again, to make the listing short, we have not checked whether any floating point overflow or underflow is there. We do not handle exceptions as well here to keep the listing brief.
 bool operator > ( const SmartFloat& other )
{ return _value > other._value; }
bool operator < ( const SmartFloat& other )
{return _value < other._value;}
bool operator == ( const SmartFloat& other )
{ return _value == other._value;}
bool operator != ( const SmartFloat& other )
{ return _value != other._value;}
bool operator >= ( const SmartFloat& other )
{ return _value >= other._value;}
bool operator <= ( const SmartFloat& other )
{ return _value <= other._value;}
The preceding code implements relational operators and most of the semantics associated with double precision floating points have been implemented as shown:
 operator int () { return _value; }
operator double () { return _value;}
};
For the sake of completeness, we have implemented conversion operators to int and double. We will write two functions to aggregate values stored in an array. The first function expects an array of double as parameter and the second one expects a SmartFloat array as parameter. The code is identical in both routines and only the type changes. Both will produce the same result:
double Accumulate( double a[] , int count ){
double value = 0;
for( int i=0; i<count; ++i) { value += a[i]; }
return value;
}
double Accumulate( SmartFloat a[] , int count ){
SmartFloat value = 0;
for( int i=0; i<count; ++i) { value += a[i]; }
return value;
}
int main() {
// using C++ 1z's initializer list
double x[] = { 10.0,20.0,30,40 };
SmartFloat y[] = { 10,20.0,30,40 };
double res = Accumulate(x,4); // will call the double version
cout << res << endl;
res = Accumulate(y,4); // will call the SmartFloat version
cout << res << endl;
}
The C++ language helps us write expressive types that augment the semantics of basic types. The expressiveness of the language also helps one to write good value types and reference types using a myriad of techniques supported by the language. With support for operator overloading, conversion operators, placement new, and other related techniques, the language has taken the class design to a higher level compared to other languages of its time. But, with power comes responsibility and the language sometimes gives you enough rope to shoot yourself in the foot.

Substitutability

In the previous example, we saw how a user-defined type can be used to express all the operations done on a built-in type. Another goal of C++ is to write code in a generic manner where we can substitute a user-defined class that mimics the semantics of one of the built-in types such as float, double, int, and so on:
//------------- from SmartValue.cpp
template <class T>
T Accumulate( T a[] , int count ) {
T value = 0;
for( int i=0; i<count; ++i) { value += a[i]; }
return value;
}
int main(){
//----- Templated version of SmartFloat
SmartValue<double> y[] = { 10,20.0,30,40 };
double res = Accumulate(y,4);
cout << res << endl;
}
The C++ programming language s...

Indice dei contenuti