Skip to content

WIP: [resolveRefs()] Unproxying and evaluation helper for `auto`.

Jö Fahlke requested to merge feature/resolve-refs into master

WIP: looks like this MR is being superseded by !345 (merged). Keeping it open for now since most of the discussion is here.

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 overloads of resolveRefs() 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 = resolveRefs(v[0]);
  v.clear();
  return head;
}

Without resolveRefs() 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 resolveRefs() ensures that the evaluation happens while the reference to the subexpression is still valid, and has not ill effect when fundamental types instead of Adept's custom types are used.

Edited by Jö Fahlke

Merge request reports