Xavier Lamorlette

C++ 11/14

Syntax Improvements

Range Based Loop

std::vector v = {0, 1, 2, 3, 4, 5};
for (const int & i: v)   // access by const reference
for (auto i: v)          // access by value: i is an int
for (auto & i: v)        // access by reference: i is an int &
for (const auto & i: v)  // access by const reference: i is a const int &

for (int n: {0, 1, 2, 3, 4, 5})  // the initialiser may be a braced-init-list

map address_book;
for (auto address_entry: address_book) {
    cout  << address_entry.first << " < " << address_entry.second << ">" << endl;
}

To enable range based loops on a custom class:

class A_iterator {
    A_iterator(const A_iterator & other);
    A & operator*();
    A_iterator & operator++() {
        […]
        return * this;
    }
};

bool operator!=(const A_iterator & lhs, const A_iterator & rhs);

class A_collection {
    A_iterator begin() const;
    A_iterator end() const;
};

User-defined and Predefined Literals

constexpr unsigned long operator""_K(unsigned long x) {
    return 1024 * x;
}
cout << 1000_K;  // => 1024000

auto s = "hello"s;          // std::string
auto t = 3h + 28min + 12s;  // t is a chrono::duration

constexpr auto tenMillion = 10'000'000;  // on peut utiliser ' pour séparer les chiffres d'un nombre

Classes

Default Class Member Initialisation

class A {
    int a[10] = {1, 2};  // non-static data member with initialiser
};

Default Methods

class A {
    A() = default;
    virtual ~A() = default;
    A(const A &) = default;
    A & operator=(const A &) = default;
    A(A &&) = default;
    A & operator=(A &&) = default;
};

Inheriting Constructor

class B: A {
    using A::A;
};

Default and copy constructors are not inherited.

Delegating Constructor

class M {
    int x;
public:
    M(int v):
        x(v) {
    }

    M():
        M(0) {
    }
};

Containers

Array: std::array

std::array = C array

Tuple: std::tuple

Tuple convenience functions:
make_tuple(t1, …, tn)

tie(t1 … tn) ~ make_tuple(ref(t1) … ref(tn)):
  int i;
  string s;
  tie(i, s) = make_tuple(3, "hello");
  tie(i, ignore) = //

Unordered Associative Arrays

Boost Polymorphic Containers

Rvalue Reference and Move Semantics

T && refRValue = …;

class A {
    A(A && other);              // move constructor
    A & operator=(A && other);  // move assignment operator
};

std::move est un cast en rvalue.

Lambda Expressions

The [] construct inside a function call’s argument list indicates the beginning of a lambda expression:
[capture](parameters) -> return-type {body}

The return type is optional if the compiler can deduce it unambiguously.

Store lambda function:

auto toto = []()->T{}

std::function t = [](int a){return a * a;};

Variadic Templates

Ce qui est devant l'oppérateur points de suspension (ellipsis operator), ..., est répété, avec une virgule entre chaque répétition :

... répète toute l'expression comprenant un parameter pack. Exemple : foo(bar(args)...).

Exemples :

template<typename T>
T Sum(T value) {
    return value;
}

template<typename T, typename... Args>
T Sum(T first, Args... args) {
    return first + Sum(args...);
}

template<typename... Args>
class Variadic_template {
    static const uint8_t size = sizeof...(Args);
};

Multithreading

thread_local: for global and static variables, separate instance of the variable for each thread.

thread_local int x;

Miscellaneous

New algorithms

#include <algorithm>

// are all of the elements positive?
all_of(first, first+n, ispositive());

// is there at least one positive element?
any_of(first, first+n, ispositive());

// are none of the elements positive?
none_of(first, first+n, ispositive());

String utilities

lexical_cast converts using stream operators. If it fails, it throws a bad_lexical_cast exception.

#include <boost/lexical_cast.hpp>
string s = lexical_cast<string>(3);

boost/format.hpp is a type safe and richer printf.

External Templates

External templates stop implicit instantiations (possibly duplicated in several translation units). It needs of course one explicit instantiation in a translation unit.

template<typename T> class A {…};
extern template class T<someType>,

Static assertion

Assertion verified at compile time.

template<typename T>
class A {
    T *_t;
    static_assert(not(is_void<T>::value, "Instantiating template class A with void");
};

Attributs

Cf Attributs.

La dernière mise à jour de cette page date de janvier 2019.

Le contenu de ce site est, en tant qu'œuvre originale de l'esprit, protégé par le droit d'auteur.
Pour tout commentaire, vous pouvez m'écrire à xavier.lamorlette@gmail.com.