mercredi 27 janvier 2016

Control to what kind of references `T` binds

While thinking about what can be done to solve the std::min dangling reference problem, one thought I had was to add an overload (actually 3 - for each combination) for rvalues that would be deleted. The issue is that T&& would be a forwarding reference, not an rvalue reference.

I want to separate this question from std::min specifically and make it more general. The std::min can be taken as an example why would you need such a thing.

Lets simplify and generalize the problem:

// this has the same problem as `std::min`: if t binds to a temporary,
// and the result is assigned to `auto&`, the result is a dangled reference
template <class T>
const T& foo(const T& t)
{
  return t;
}

// incorrect attempt to prevent foo from being called with a temporary argument
// `T&&` is a forwarding reference, not a rvalue reference
template <class T>
const T& foo(T&& t) = delete;

The question is: How can you control to what kind of references a generic template parameter T could bind?

Aucun commentaire:

Enregistrer un commentaire