cpp11.html 13.2 KB
Newer Older
Praetorius, Simon's avatar
Praetorius, Simon committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
<!DOCTYPE html>
<html>
  <head>
    <title>AMDiS - Adaptive Multi-Dimensional Simulations</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <style type="text/css">
      @import url(https://fonts.googleapis.com/css?family=Yanone+Kaffeesatz);
      @import url(https://fonts.googleapis.com/css?family=Raleway);
      @import url(https://fonts.googleapis.com/css?family=Ubuntu);
      @import url(https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic);
      @import url(https://fonts.googleapis.com/css?family=Ubuntu+Mono:400,700,400italic);

      table tr:nth-child(even) {
          background-color: #eee;
      }
      table tr:nth-child(odd) {
          background-color: #fff;
      }
      table tr td {
        padding: 10px;
        border-left: 1px solid #aaa;
      }
    </style>
    <!--<link rel="stylesheet" type="text/css" href="style_display.css" />-->
    <link rel="stylesheet" type="text/css" href="style_print.css" />
  </head>
  <body>
    <textarea id="source">

class: center, middle

# Session 13
## `C++11` - and overview
### How to use the new language features in AMDiS

---

# Agenda

### Friday
- **Using `C++11` with AMDiS**
- Extensions
- Software Development and Workflow (Ansgar Burchard)
- AMDiS User-Group meeting
- Presentation of Student Projects

(Some notes are taken from presentation of Rainer Grimm)

---

class: center, middle

# Bjarne Stroustrup about `C++11`

*„Surprisingly, `C++11` feels like a
new language - the pieces just fit
together better.“*

---

# History

- `C++98`: first ISO standard
  - `C++03`: technical corrigendum
  - TR1: technical report 1
- `C++11`: accepted in August 2011
- `C++14`: current ISO standard
- `C++1z`: future ISO standard (maybe 2017)

---

# Design goals of `C++11`

`C++` has from its inception been a general-purpose programming language with a bias towards systems programming that

- is a better C
- supports data abstraction
- supports object-oriented programming
- supports generic programming

### The overall aims for `C++11`:

- Make `C++` a better language for systems programming and library building
- Make `C++` easier to teach and learn
- Very stringent compatibility constraints.

### General principles of `C++`
- Trust the programmer.
- You don't have to pay for something you don't need.
- Don't break existing code.
- Prefer compile time errors over run time errors.

---

# auto

For variables, specifies that the type of the variable that is being declared
will be automatically deduced from its initializer. For functions, specifies that
the return type is a trailing return type.

### Examples
```
auto x = 1.0 + f(2.0);
auto iter = vector.begin();     // Iterator
auto expr = valueOf(u) + X(0);  // AMDiS-Expression
```

### Deduction rules:
When auto sets the type of a declared variable from its initializing expression, it proceeds as follows:

1. If the initializing expression is a reference, the **reference is ignored**.
2. If, after Step 1 has been performed, there is a **top-level const** and/or volatile qualifier, it **is ignored**.

---

# decltype

`decltype( expr )` inspects the declared type of an entity or the type and value category of an expression.

### Examples:
```
int x;
const int cx = 42;
const int& crx = x;

typedef decltype(x) x_type; // int
auto a = x; // int

typedef decltype(cx) cx_type; // const int
auto b = cx; // int

typedef decltype(crx) crx_type; // int const&
auto c = crx; // int
```

1. If `expr` is a is a plain, unparenthesized variable, function parameter, or
   class member access, then `decltype(expr)` is the type of that variable,
   function parameter, or class member as declared in the source code.
2. Let `expr` be an expression that is not as in 1. Let `T` be the type of `expr`.
   If `expr` is an *lvalue*, then `decltype(expr)` is `T&`. If `expr` is an
   *xvalue*, then `decltype(expr)` is `T&&`. Otherwise, `expr` is a *prvalue*,
   and `ecltype(expr)` is `T`.

---

# auto + decltype

Use a combination of both for functions with trailing return type:
```
template <class T1, class T2>
auto f(T1 a, T2 b) -> decltype( a*b );
```
where the return-type of the function is deduced from the expression involving `a` and `b`.

### Can be used to declare functions returning an AMDiS expression.
```
struct A {
  DOFVector<double>& u;

  template <class E>
  auto add(E expr) -> decltype( valueOf(this->u) + expr )
  {
    return valueOf(u) + expr;
  }
};
```


(See [C++ auto and decltype Explained](http://goo.gl/9KxeDP) for details
about `auto` and `decltype` specifier. Some of the statements are taken from there.)

---

# Lambda expression
Lets you define functions locally, at the place of the call, and has the form:
```
[capture](parameters) -> return_type { body }
```

### Example: Dirichlet condition
```
prob.addDirichletBC(boundaryNr, 0, 0,
  [](WorldVector<double> const& x) { return std::sin(x[0]); });
```
--

- Use capture list can be used to include variables from the sourrounding scope to the function scope:
  ```
  int var = 1;
  auto f = [var](double x) { return var*x; };
  ```
- Return type can be ommited, if only one return statement in function body.
- lambda expression can be stored in variables, using `auto` type deduction
- lambda expression can be assigned to `std::function`:
  ```
  std::function<double(double)> f = [](double x) { return x + 1.0; };
  ```

---

# Lambda expressions

Wrap a lambda expression to use it in place of an arbitrary `AbstractFunction`s
```
template <class ReturnType, class... ArgumentTypes>
class LambdaFunction
  : public AbstractFunction<ReturnType, ArgumentTypes...>
{
public:
  template <class F>
  LambdaFunction(F&& fct) : fct(std::forward<F>(fct)) {}

  virtual ReturnType operator()(ArgumentTypes const&... args) const override
  {
    return fct(args...);
  }

private:
  std::function<ReturnType(ArgumentTypes...)> fct;
};
```
Usage:
```
DOFVector<double> u = ...;
u.interpol(new LambdaFunction<double, WorldVector<double>>(
  [](WorldVector<double> const& x) { return std::sin(x[0]); }) );
```

(See *variadic templates* for details about the handling of the template arguments)

---

# Range based for loops

The range-based for loop has the following form:
```
for ( declaration : expression ) statement
```
with `declaraion` a statement to declare a variable thar represents the elements
of a container or list `expression`. The `statement` can contain the declared
variable.

### Example:
```
int array[5] = { 1, 2, 3, 4, 5 };
for (int&amp; x : array)
  x *= 2;
```
or simply
```
for (int x : { 1, 2, 3, 4, 5 })
  std::cout << x << "\n";
```

---

# Range based for loops
### Using range based loops with AMDiS iterators.

A range-based loop is internally translated to
```
{
  auto&amp;&amp; __range = expression;
  for (auto __begin = begin_expr, __end = end_expr;
        __begin != __end; ++__begin)
  {
    declaration = *__begin;
    statement
  }
}
```
where `begin_expr` and `end_expre` are either
```
__range.begin()
__range.end()   // if found as member, otherwise
begin(__range)
end(__range)    // found by argument dependend lookup
```
Thus, the containers we want to iterate over (e.g. DOFVector, Mesh) must provide
these `begin(), end()` method.
- `DOFVector` has `begin()` and `end()` that point to the unterlying `std::vector`

---

# Range based for loops
### Provide a DOFIterator wrapper

```
template <class Container>
class DofRange
{
  using T = typename Container::value_type;

  template <class Vector, class Iter> struct Iterator { /* ... */ };

  using  ConstIter   = Iterator<DOFVector<T> const, DOFConstIterator<T>>;
  struct MutableIter : Iterator<DOFVector<T>, DOFIterator<T>> { /* ... */ };

public:
  DofRange(Container& vec, DOFIteratorType flag) : vec(vec), flag(flag) {}

  std::conditional_t<std::is_const<Container>::value, ConstIter, MutableIter>
  begin() const {
    return {vec, flag, false};
  }

  std::conditional_t<std::is_const<Container>::value, ConstIter, MutableIter>
  end() const {
    return {vec, flag, true};
  }

private:
  Container& vec;
  DOFIteratorType flag;
};
```

---

# Range based for loops
### Provide a DOFIterator wrapper

Usage:
```
template <class Vector>
DofRange<Vector> used_dofs(Vector& vec)
{
  return {vec, USED_DOFS};
}

// ...

DOFVector<double>& u = *prob.getSolution(0);

int i = 0;
for(auto& x : used_dofs(u))
  x = i++;
```

(Details can be found in `extensions/cpp11/DofRange.hpp`)

---

# Range based for loops
### Provide a Mesh Traversal wrapper

```
class MeshTraversal
{
  struct Iterator;

public:
  MeshTraversal(Mesh* mesh, Flag flags)
    : mesh(mesh)
    , flags(flags)
  {}

  Iterator begin() const {
    return {mesh, flags, false};
  }

  Iterator end() const {
    return {mesh, flags, true};
  }

private:
  Mesh* mesh;
  Flag flags;
};
```

---

# Range based for loops

with `MeshTraversal::Iterator` defined by
```
struct Iterator
{
  Iterator(Mesh* mesh, Flag flags, bool end = false)
    : end(end)
  {
    if (!end) {
      stack.reset(new TraverseStack);
      elInfo = stack->traverseFirst(mesh, -1, flags);
    }
  }
  Iterator(Iterator&&) = default;

  ElInfo const* operator*() const { return elInfo; }
  ElInfo*       operator*()       { return elInfo; }

  bool operator==(Iterator const& other) const;
  bool operator!=(Iterator const& rhs) const;

  Iterator& operator++() { elInfo = stack->traverseNext(elInfo); return *this; }

protected:
  std::unique_ptr<TraverseStack> stack;
  ElInfo* elInfo = nullptr;
  bool end;
};
```

---

# Range based for loops
### Provide a Mesh Traversal wrapper

Usage:
```
MeshTraversal traverse(Mesh* mesh, Flag flags = 0)
{
  return {mesh, Mesh::CALL_LEAF_EL | flags};
}

// ...

Mesh* mesh = prob.getMesh();
for (ElInfo* elInfo : traverse(mesh)) {
  std::cout << elInfo->getElement()->getIndex() << "\n";
}
```

(Details can be found in `extensions/cpp11/MeshTraversal.hpp`)

---

# Variadic templates

A template parameter pack is a template parameter that accepts **zero or more
template arguments** (non-types, types, or templates). A function parameter pack
is a function parameter that accepts **zero or more function arguments**. A template
with at least one parameter pack is called a *variadic template*.
```
template <class... Ts>
struct Tuple { /* ... */ };

template <class... Args>
??? min(Args const&... args) { /* ... */ }

template <int... Ints>
struct IntSeq;
```
The three dots `...` induce an expansion of the parameter pack (pattern) directly before the
three dots to a list of arguments.

- An individual type (argument) can not directly be accessed.
- Work with variadic templates is based on recursion
- Break condition is based on fixed number of arguments (or empty list)
- No runtime-overhead due to variadic argument list

---

# Variadic templates

### Example: Access to tuple element.
```
template <size_t i, class TupleType> Get;

template <size_t i, class T0, class... Ts>
Get<i, Tuple<T0, Ts...>> : Get<i-1, Tuple<Ts...>> {};

template <class T0>
Get<0, T0> { using type = T0; };
```

### Example: minimum of many arguments
```
template <class Arg0, class Arg1>
auto min(Arg0 const& a, Arg1 const& b) -> decltype( a < b ? a : b )
{
  return a < b ? a : b;
}

template <class Arg0, class... Args>
auto min(Arg0 const& a, Args const&... args) -> decltype( min(a, min(args...)) )
{
  return min(a, min(args...));
}
```

---

# Variadic templates
## AMDiS examples

`1.` functor expression with arbitrary number of arguments
```
template <class F, class... Terms>
typename result_of::FunctionN<F, Terms...>::type
func(F const& f, Terms... ts) { /* ... */ }
```
Usage:
```
DOFVector<double> u = ...;
u << func([](Arg1 arg1, Arg2 arg2 /*...*/) { /*...*/ },
          expr1, expr2 /* ... */);
```
where `Arg1` is the `value_type` of `expr1`, and so on.
--


**Remark:** The functor expression implements `LazyOperatorTerms`:

```
template <class... Terms>
class LazyOperatorTerms : public LazyOperatorTermBase
{
  std::tuple<Terms...> term_tuple;
};
```


---

# Variadic templates
## AMDiS examples

`2.` Abstract functions with many arguments
```
template <class ReturnType, class... Args>
class AbstractFunction
{
public:
  /* ... */
  virtual ReturnType operator()(Args const&... args) const = 0;
};
```

`3.` A `CouplingBaseProblem` for different `BaseProblem` types:
```
template <class ProblemType=ProblemStat, class... BaseProblemTypes>
class CouplingBaseProblem
    : public CouplingIterationInterface,
      public CouplingTimeInterface,
      public AMDiS::detail::CouplingProblemStat<ProblemType> { /*...*/ };
```

`4.` AMDiS requires the constant `HAS_VARIADIC_TEMPLATES` to be set to 1
(is automatically set for the most of the compilers in `Config.h`).


    </textarea>
    <script src="lib/remark.js" type="text/javascript"></script>
546
    <script type="text/javascript" src="MathJax/MathJax.js?config=TeX-AMS_HTML"></script>
Praetorius, Simon's avatar
Praetorius, Simon committed
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569

    <script type="text/javascript">
      var slideshow = remark.create({
        ratio: "4:3",
        highlightLanguage: "cpp"
      });

      // Setup MathJax
      MathJax.Hub.Config({
          tex2jax: {
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre']
          }
      });
      MathJax.Hub.Queue(function() {
          $(MathJax.Hub.getAllJax()).map(function(index, elem) {
              return(elem.SourceElement());
          }).parent().addClass('has-jax');
      });

      MathJax.Hub.Configured();
    </script>
  </body>
</html>