Skip to content
Snippets Groups Projects
Commit 62ec1946 authored by Jö Fahlke's avatar Jö Fahlke
Browse files

[autoCopy()] Unproxying and evaluation helper for `auto`.

This introduces a helper function that enables `auto` type deduction even in
the presence of proxies and pre-C++11 libraries with a tendency to capture
references to temporaries.

Note: the motivating examples below make use of specializations of
      `autoCopy()` that will be introduced in later commits.

Example 1: deducing the element type of a vector when proxies are a
possibility:
```c++
template<class Vector>
auto pop_and_clear(Vector &v)
{
  auto head = autoCopy(v[0]);
  v.clear();
  return head;
}
```
Without `autoCopy()` this would be undefined behaviour if `Vector` happens to
be `std::vector<bool>`.

Example 2: a custom number type with lazy evaluation:
```c++
template<class MaybeCustomType>
auto f(MaybeCustomType v)
{
  return 2 * v - 1;
}
```
This fails for the custom number type from the automatic differentiation
library Adept, because Adept constructs an expression object that holds
references to its subexpressions and is evaluated only when it is assigned to
a number object later.  Due to the use of `auto` this expression object is
passed out of the function, but the temporary object for the subexpression
`2*v` is destroyed when the function returns.  Wrapping the expression in the
`return` statement with `autoCopy()` ensures that the evaluation happens while
the reference to the subexpression is still valid, and has no ill effect when
fundamental types instead of Adept's custom types are used.
parent 02ea3efb
No related branches found
No related tags found
1 merge request!345[autoCopy()] Unproxying and evaluation helper for `auto`.
Pipeline #
Loading
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment