[autoCopy()] Unproxying and evaluation helper for `auto`.
Intended merge date: 2017-11-13.
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:
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:
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.