Report from using std::cpp 2016

Last November 24th we had the fourth edition of using std::cpp, our annual conference on C++ for professional developers. The conference is a one-day free event held every year at University Carlos III of Madrid, in Leganés. We had around 200 registered attendees (most of them professional developers).

Who were our attendees

This year most of the attendees were coming from the Madrid region. However, we had attendees from many other regions in Spain.

We would like to share some answers from the evaluation questionaries:

  • 75% of attendees were professional developers, 14% were students, and 11% were academics.
  • 92% declared they use regularly C++.
  • The most popular version of C++ was C++11 (73%), followed by C++98/03 (63%) and C++14 (21%). Note that you could vote for more than one. However, no one declared to make use of any extension or TS.
  • Most popular compiler was gcc (60%), followed by Microsoft (57%), and clang++ (14%).
  • When we asked for domains a found a split among multiple sectors: telco (20%), aerospace/naval (11%), civil engineering (9%), bank/finance/insurance (7%), developer tools (7%), videogames (6%), research/academia (4%), transport (4%), industrial manufacturing (2%).

Our talks in 2016

Here is a summary of the talks we had:

  • C++17 is (almost) here. J. Daniel García (ARCOS Lab, University Carlos III), member of ISO C++ standards committee and associate professor in Computer Architecture.
    This talk presented some of the  features that are highly likely to be present in the upcoming C++17.
  • Get your types to work. Joaquin M. López, software developer and contributor of several Boost libraries (example, Boost multi-index).
    Joaquín showed how we can make use of the type system to prevent programming mistakes moving defects detection from execution time to compile-time. You may find slides in English here.
  • C++ and much more. An overview to the available libraries universe. Martin Knoblauch (Indizen Technologies), a software developer in the finance sector.
    Martin made a list of C++ libraries that he recommends to use. He gave some brief overviews of Google protocol buffers, flat buffers, Zero Message Queue, TBB, CUDA, Boost and GSL.
  • Test Driven Development in C++. Raúl Huertas (TCP Sistemas), a software developer with long background in the telecom business.
    Raúl made a practical introduction to TDD through a number of examples in form of short tutorial. He used catch library in all examples.
  • Using C++ in safety critical embedded systems for railways. Ion Gaztañaga (CAF), another Boost contributor (example, Boost Interprocess).
    Besides being a very experienced and well known C++ developer, he works professionally developing software for railway systems. He focused his talk in providing details on the constraints in safety critical systems. He explained also which subset of C++ you are able to use when you have to comply with safety regulations.
  • At a Matlab breakdown… Save me C++! Javier Garcia-Blas (ARCOS Lab, University Carlos III), visiting professor in Computer Architecture.
    Javier showed how to port existing MATLAB applications to C++ mixing the use of several C++ libraries: Armadillo and ArrayFire. He provided details on how he used those libraries for porting magnetic resonance image processing.
  • Static and dynamic polymorphism in C++11: Flexibility versus performance?. J. Daniel Garcia (ARCOS Lab, University Carlos III), member of ISO C++ standards committee and associate professor in Computer Architecture.
    Following a number of examples J. Daniel transitioned from a canonical object oriented solution to a problem to a type erased solution finishing with an implementation of the small object optimization.
  • Using templates in C++ to design and implement. Jose Caicoya (Hotel Beds), software developer with background in real-time systems, finance and, more recently, hotel reservation systems.
    Jose followed through a number of examples different uses of templates.
  • Distributed systems: How to connect your real-time applications. Jaime Martin (eProsima), developer of an open source DDS impelementation.
    Jaime made a short introduction to DDS providing examples on its use to build distributed systems highlighting the C++ mapping.
  • Developing an reflection system for C++14. Manu Sanchez (ByTech), software developer and metaprogrammer.
    Finally Manu Sanchez presented his results in trying to build a reflection solution by using libclang.

After reviewing the evaluations we want to congratulate Joaquin M. Lopez for having the best evaluated talk this year.

Acknoledgments

We want to thank many people who helped to make using std::cpp again a reality.

Our first thanks go to Indizen. This company has been helping us in the organization of this event year after year from the first edition.

We also want to express our gratitude to JetBrains. Again this year they have contributed by giving a number of licenses of CLion that we have given out in a draw.

Of course, we also want to express our thanks to all the speakers in this year’s edition. They were crucial in attracting the audience and all the talks were highly evaluated by attendees.

Finally, we want to thank to the volunteers who helped in the organization.

Publicado en misc, Trip Reports | Etiquetado ,

C++: Oulu Trip Report (Part I)

The 2016 summer C++ standards meeting is over. This meeting has the record to be (at least to my knowledge) the northest meeting we have ever had. According to several sources the distance from the venue to the Arctic circle was around 100 KM. It was really shocking to have no night at all. It did not matter what your clock said, the sun was almost always around.

So, what has happened here? Well the big headline is that we approved to issue the CD (committee draft) for C++17. Now we will have a period where national standards bodies will have the opportunity (and are expected) to issue comments on every page of the standard. Those comments will be processed in the next meeting to be held in November in Issaquah (Washington, USA).

So. If you have any comments, contact to your standards national body. In case you are Spanish, please contact me.

Now I will try to summarize the new additions that we approved for c++17. However do not expect that this post contains an exhaustive list. I leave that to others. My list is based on things I can easily state in post and that I consider interesting for most developers. Or things, that I am interested for some particular reason.

In this post you will find the language part. You will have to wait for the library part a few days more.

Here is my list:

  1. We now can use attribute namespaces without repeating the namespace in front of every attribute. For this we have a new prefix using in attributes.
    [[using rpr: kernel, target(gpu), in(x), out(y,z)]]
    // Same as 
    // [[rpr::kernel, rpr::target(gpu), rpr::in(x), rpr::out(y,z)]]
  2. A new form of operator new, takes and additional parameter of type std::align_val_t to be used with over-aligned data types.
  3. The rules for template argument deduction currently valid for functions have been extended so that now can be applied to constructors:
    std::pair p{3.5, 2}; // p is pair<double,int>
    std::mutex m;
    auto l = std::lock_guard{m}; // l is lock_guard<std::mutex>
  4. Non-type template parameters can be declared with auto. This allows to write simpler templates:
    // C++14
    template <typename T, T v> struct S { /*...*/ };
    S<decltype(x), x> s;
    
    // C++17
    template <auto v> struct S { /*...*/ };
    S<x> s;
  5. While there is a number of cases where copy elision is optional in C++, C++17 makes it mandatory for the case where a temporary object is used to initialize another object. This happens, for example, when a temporary is returned from a function.
  6. The order of evaluation of some expressions is now fixed. This solves problems with very idiomatic constructs whose order of evaluation is not fixed in C++14.
    s.replace(0, 4, “”).replace(s.find(“even”), 4, “only”).replace(
        s.find(“ don’t”), 6, “”);

    Note that not all orders are fixed. In particular it is still not fixed the order in which function arguments are evaluated.

  7. While the use of attributes and scoped attributes that are not defined in the standard is still implementation defined, the use of attributes that are not recognized by an implementation should be ignored. This allows that tools can define attributes in their own namespace without risk that a compiler issues errors because of that.
  8. A compile-time solution for if is provided through if-constexpr which allows that template code is instantiated depending on compile-time condition.
    template<typename T, typename ... Rest> 
    void g(T&& p, Rest&& ...rs) {
      if constexpr (sizeof...(rs) > 0)
         g(rs...); // never instantiated with an empty list.
     }
  9. The inline specifier can now be applied to variables. Those variables can be defined in multiple translation units (with exactly the same definition) and generate a single variable. Static data members which are constexpr are implicitly inline.
    class X {
      constexpr static int max = 10;
      //...
    };
    
    const int X::max; // No longer needed

    This also allows to define global variables in header files without needing a definition in some translation unit.

    // Header A.h
    inline int x=42;
    
    // Header B.h
    inline int x=42
  10. Structured bindings allow to get multiple values returned by a function in multiple variables.
    tuple<int,string> f();
    auto [x, y] = f();  // x->int, y->string
    
    struct A {
      int n;
      double x;
      char c;
    };
    A g();
    
    auto [x,y,z] = g();
  11. If and switch statements may now include an initialization before the condition that has the scope of that statement.
    if (int x = get_value(); x>0) {
      use(x);
    }
    
    switch (auto z = get_enum(); z) {
      case val1: do_something(z); break;
      case val2: do_other(z); break;
    }
Publicado en Lenguaje C++, misc, Trip Reports | Etiquetado ,

Trip report: C++ meeting at Jacksonville

First of all the bad news. Unfortunately I have to say that the outcome of the standards meeting has been disappointing. Let me explain myself. We had a really very intense week here in Jacsonville. We made progress in many things, but  we will not have the killer features I really wanted for C++17.

Not for C++17

Let me start enumerating the things we are not going to have in C++17:

  • Modules: They will not be in C++17, but in a separate technical specification. That is really a pity, as we will be for more years without having what I was expecting to let me get rid of the text substitution paradigm of the include directive as well as improve compilation times.
  • Concepts: They will not be integrated in C++17, but stay for now in their own technical specification. There were concerns about some issues in the TS, which I do not consider essential. Despite that there is implementation experience and even other TS depends on it, it was rejected to move concepts to the IS.
  • Ranges: This is a library solution highly depending on concepts. So, no way.
  • Coroutines: There was a very sound proposal with implementation experience. However, again this was targeted to another technical specification.

Besides that, we also will not have the half of uniform function call syntax that I thought was not controversial. To be clear, I really wanted both halves.

A different case is contracts, where I think we made progress an achieving a unified proposal, however this needs more work before being able to target C++ (either a TS or the next release of C++ after C++17).

Some good news

Still there are good news in terms of major features. We decided to incorporate to C++17 the technical specification for parallelism. That is something! It means that we will be able to use parallel versions of many standard library algorithms and getting the performance of their parallel and vectorized versions.

C++17 will include what was a separate international standard (ISO/IEC 29124:2010). Consequently you will be able to rely on any C++17 implementation to make use of functions like Bessel functions, Legendre polynomials, Hermite polynomials or Riemann zeta function.

Finally, C++17 will also include the file system technical specification providing a modern library solution to access to the file system.

C++17 major or minor

All in one this means that C++17 is seen by me as a minor update. I agree we will have some nice features. But I also think that we have set a very high threshold for setting new things in the C++ standard. Some people seriously questioned features that had been used for a decade with multiple implementations.

If C++ had used this threshold in the past we would probably had delayed many of the features that today are part of C++ (templates and STL come to my mind).

Some may say that we could see that C++17 plus the accompanying technical specifications make a good set and users will be able to use all of them. However, for many organizations TS are seen as experimental features they are not willing to use in production code. And they are sometimes right.

Some accepted features

As I do not want to be so negative, let me tell what was approved to be in C++17.

Fall-through in switch statements

You now may explicitly say that a case branch wants to fall-through and that you did not forget the break:

switch (n) {
case 1:
case 2:
  f1();
  [[fallthrough]];
case 3: // Hopefully no warning
  f2();
  break;
case 4: // No warning 
  f3();
case 5: // Hopefully warn on fallthrough
  f4();
  [[fallthrough]]; // ill­formed
}

Avoiding discarding results

You may want to issue a warning when you do not use the result of a function.

struct [[nodiscard]] mytype { /*...*/ };
mytype f();
[[nodiscard]] int g();
void g() {
  f(); // warning: result discarded
  auto x = f(); // OK.  
  f(); // warning: result discarded
  auto x = g(); // OK.
}

Unused value

Unused warnings are useful but sometimes you really want to avoid them

void f() {
  int x; // warning: unused
  int y; // warning in non-deubg mode
  assert(y==0); 
}

void g() {
  [[maybe_unused]] int x; // avoid warning
  [[maybe_unused]] int y; // avoid warning
 assert(y==0);
}

Extending aggregate initialization

Aggregate initialization has been extended to support inheritance avoiding the need to define boilerplate constructors.

struct A {
  int x;
};

struct B : A {
  double y;
};

void f() {
  A a{2};
  B b { {1}, 2}; // b.x=1, b.y=2
  B b { {}, 2};  // b.x=0, b.y=2
}

Constexpr lambdas

Lambda expressions can be used on constexpr contexts:

constexpr int f(int x) {
  return [x] { return x+10; }
}

This also means that now a lambda expression can be constexpr itself. However, if the contexpr specifier is omitted when it satisifes requrements for constexpr.

auto f = [](int x) constexpr { return x; }
auto g = [](int x) { return x; }
constexpr z1 = f(2);
constexpr z2 = g(2);
int y = get_value();
constexpr z3 = f(y); // Ouch!
constexpr z4 = g(y); // Argh!

Removing unary folds

Unary folds have defaults in empty parameter packs. Some of them (*, +, &, |) have been removed as they could lead to surprising results.

template <typename ... Args>
auto sum1(Args ... args) {
  return (args+...); // Ill formed: No default
}

template <typename ... Args>
auto sum2(Args ... args) {
  return (args+...+0); // OK: Default provided
}

Generalized for range loop

Range based for loops may now have different types for begin and end.

{
 auto && __range = for-range-initializer;
 auto __begin = begin-expr;
 auto __end = end-expr;
 for ( ; __begin != __end; ++__begin ) {
   for-range-declaration = *__begin;
   statement
 }
}

Capturing *this by value

A new capture for this has been added to lambda expressions. While capturing this, captures the this pointer,  *this captures by copy.

auto f = [*this]() { /* ... */ } // captures by copy

Construction rules for enum values

We now allow implicit/non-narrowing conversions from a scoped enumeration’s underlying type to the enumeration itself, when its definition introduces no enumerator and the source uses a list-initialization syntax. This is safe and support very useful programming techniques. For example, you could introduce new integer types that enjoy the same existing calling conventions as its underlying integer type.

enum class my_integer : int {};
struct A {
  my_integer value;
};
A a = { my_integer{17} };

void f(my_integer};
void g() {
  f(my_integer{24});
  // ...
}

Hexadecimal floating point literals

Now you can express floating point literals in hexadecimal.

float x = 0xC.68p+2; // 49.625

Asking about lock-free at compile time

As a complement of is_lock_free() a static constexpr counterpart is now provided. Now atomic types have a new static constexpr bool named is_always_lock_free

static_assert(!atomic<T>::is_always_lock_free, "No lock free");

This is also useful to be used in enable_if contexts.

New traits for swappable and nothrow-swappable

New traits have been added and used for swap functions.

  • is_swappable_with<T,U>
  • is_swappable<T>
  • is_nothrow_swappable_with<T,U>
  • is_nothrow_swappable<T>

Clamping values

Function clamp ensures to make a value fit withing two bounds.

int x 10;
int y1 = clamp(x,5,8); // y1=8
int y2 = clamp(x,15,20); // y2=15
int y3 = clamp(x,5,15); // y3 = 10

Other library improvements

  • A better and more precise specification for enable_shared_from_this.
  • The addition of predicate not_fn from the library fundamentals TS.
  • Changes to searchers interfaces.
  • A portable way of accessing cache line sizes through hardware_destructive_interference_size and hardware_constructive_interference_size.
  • A new overload to std::hypot to be able to to take 3 arguments which makes easy to compute distance between 2 3D points.
  • A number of constexpr additions to iterators.
  • A non const version of data member function of std::string.
  • Additional traits std::is_callable and std::is_nothrow_callable.

 

Publicado en misc, Sin categoría

Oferta de empleo en Indizen Technologies

La empresa Indizen me pasa la siguiente oferta de empleo

Ingeniero C++

Descripción: Buscamos especialistas en desarrollo de C++ para proyecto estable en el área de Investigación. Valoramos las titulaciones de Ingeniero Técnico o Superior, alta capacidad para el desarrollo a bajo nivel, orientación a objetos y fuerte base metodológica para proyecto de alta complejidad.

Requisitos:

  • BOOST, PoCo, STL.
  • Programación en C.
  • C++ 11/14.
  • Patrones de diseño.
  • Programación concurrente.
  • Herramientas de depuración: GDB, Purify…
  • Orientación a objetos.
  • Valoraremos la experiencia o conocimientos en Java, Python y programación de BBDD.

Si estáis interesados podéis enviar vuestro CV a rrhh@indizen.com.

Publicado en misc

Charla en codemotion: La herencia es la clase base de todos los problemas

Este fin de semana he estado en codemotion, el mayor evento de programadores que conozco en España. Había 8 tracks en paralelo y además otros 4 tracks de talleres. En total 2000 asistentes durante un viernes y un sábado desde por la mañana hasta por la noche. ¡Espectacular!

Después de asistir a un par de charlas, mi percepción era que a mi charla iban a venir cuatro gatos. Ya sabéis todo muy Web, Java, Javascript, y tal. Total que yo iba deambulando por los pasillos pensando eso de ¿Qué hace un programador como yo en un sitio como este?

Entonces fui a la sala que me había tocado para dar la charla. Casi 15 minutos antes me costó entrar. Mi intuición era que los de la charla anterior (una cosa muy cool relacionada las arquitecturas de las aplicaciones). Al final, conseguí entrar a mi propia charla. Y mi sorpresa fue mayúscula cuando minutos antes de la charla ya no se podía entrar y había gente sentada en el suelo (algunos) y muchos más de pie.

codemotion1codemotion2

Comencé advirtiendo que la charla era una repetición con modificaciones de una charla que había dado un año antes en Valladolid. También advertí que habría C++. Dije, este es el momento. Ahora se van a largar todos y me voya quedar con cuatro amigos y dos ex-alumnos. Pero solamente vi salir a dos personas. Como la gente seguía allí de pie, no tuve más remedio que dar la charla.

La verdad es que me lo pasé muy bien. Y me encontré con una audiencia bastante interesada. Ese mismo día ya empecé a tener mensajes pidiendo el material así que aquí lo tenéis.

La herencia es la clase base de todos los problemas

Muchas gracias a todos, por vuestra participación y por las interesantos conversaciones que pude mantener con algunos después de la charla.

Publicado en eventos

Trip report: using std::cpp 2015

For the third year in a row, we had a C++ day in Spain. Our local event using::std cpp 2015 starts to consolidate as an annual event for the Spanish C++ community. Each Fall more than 100 developers join some academics and students to exchange experiences about using C++.

using std::cpp 2015

DISCLAIMER: Please, note that all talks where given in Spanish. We will be publishing the slides and videos in the next days. However, we feel that this activity is of interest for a wider audience.

This year I opened the event with a short talk giving a subjective view of what could there be (or not) in C++17, as well as providing updates on the status of different C++ technical specifications.

Joaquín M. López, from Telefónica (also a well known contributor to Boost) provided a lot of insights on the effects of processor caches for C++ programmers. The talk provided a high level view of the needed hardware concepts. Then Joaquin focused in providing many C++ examples and how they could be reworked to take advantage of cache behavior to improve performance.

Jesus Megía, software engineering leader at Tecnobit (a spanish space and defense company) showed how they use continuous integration in their projects. The talk provided a very nice view on how they combine open source and commercial products in their software development pipeline. According to several attendees this gave them new ideas in how to combine different tools and also made them aware of tools they did not know.

Pablo San Segundo, an associate professor at Madrid Technical University, gave a talk on graph coding by means of bit strings and their industrial applications. He illustrated all the examples with his own libraries bitscan and graph.

Luis M. Sanchez, a researcher at University Carlos III introduced the audience to the new parallelism technical specification. He presented the currently approved library solution for parallelism and provided with different small examples showing that the average programmer can benefit from parallelism in different use cases.

Jose Manuel Caicoya, a software engineer from INDRA Sowftware Labs specialized in air traffic control systems, provided a talk on move semantics. The talk had the special value of coming from a practitioner and focused on how they are using move semantics in real applications and the benefits they are getting from this.

I could not resist to give a talk myself. I gave my very personal view on contracts programming. I focused on general concepts and approaches. I also provided some hints on how a contracts programming language extension could be and tried to identify where some problems are.

Manu Sánchez, also provided a basic introduction to concepts. Manu is well known as a metaprogrammer. Nevertheless, he made a simplification effort to show the basics of concepts TS.

Finally, we had a final round-table to have an open discussion on C++ present and future. In this talk, we were able to hear opinions from the above mentioned Jose Manuel Caicoya, giving his view from the aerospace application domain. Iván Gálvez from BQ (a Spanish company not only manufacturing smartphones and tablets) gave the viewpoint from a consumer electronics company. Finally Juan Morales from BBVA (a major Spanish bank) gave the viewpoint from a financial institution. Then we opened participation to public.

11 hours and 30 minutes after we had started we had to invite people to leave the room. Although, I would say a bunch still wanted more. 🙂

Publicado en eventos

Sorteo de CLion entre asistentes a using std::cpp 2015

La empresa JetBrains se une a using std::cpp 2015. Como probablemente muchos sabréis, JetBrains es la empresa que está detrás del entorno de desarrollo CLion (https://www.jetbrains.com/clion/).

JetBrains nos ha dado la oportunidad de sortear cinco licencias del producto CLion entre los asistentes a using std::cpp 2015.

Para ello, vamos a utilizar las siguientes reglas, que esperamos sean suficientemente simples:

  1. A lo largo de las sesiones en distintos momentos procederemos a realizar cada uno de los sorteos.
  2. Solamente serán elegibles para participar en el sorteo aquellos asistentes registrados que se encuentren en la sala en el momento de realizar el sorteo. Si la persona seleccionada no se encuentra en ese momento en la sala se procederá a seleccionar otra persona, otra vez por sorteo.
  3. No serán elegibles para participar en el sorteo cualquier persona que sea personal de la Universidad Carlos III de Madrid.
  4. El sorteo se realizará ejecutando un programa de generación de números aleatorios uniformemente distribuidos usando la biblioteca de número aleatorios de C++11. El código se publicará previamente.

Sobre CLion: CLion es un IDE de plataforma cruzadas para C y C++ desarrollado y distribuido por JetBrains. Soporta nativamente C y C++, incluyendo el estándar C++11, libc++ y Boost. Se apoya en el bien conocido sistema de construcción CMake y ofrece muchas caracterísitcas que hacen la vida de los desarrolladores más sencilla (navegación de código, refactorizaciones, análisis de código al vuelo y mucho más).

Sobre JetBrains: JetBrains tiene pasión por hacer que los desarrolladores sean más productivos. Diseña herramientas de desarrollo inteligente para simplificar sus tareas más desafiantes y a automatizar las más sencillas, facilitando el desarrollo.

Publicado en eventos