8

I was looking at the API for std::optional<T> on cppreference. I was curious how value_or would work. Looking there, it seems there are two overloads:

template< class U > 
constexpr T value_or( U&& value ) const&;

template< class U > 
T value_or( U&& value ) &&;

What are the const& and && trailing the function declaration? What is the difference between declaring a function as const and declaring it as const&?

Cassio Neri
  • 17,293
  • 5
  • 43
  • 66
Yuushi
  • 22,789
  • 6
  • 58
  • 73
  • This is actually a C++11 feature that compilers have recently gained support for. – chris Sep 05 '13 at 04:04
  • @chris Cheers. I knew of rvalue references to *this, but since it's probably one of the last features to be implemented, I hadn't bothered looking into them at all. – Yuushi Sep 05 '13 at 04:32
  • @chris honestly I'd been waiting to answer this question I saw the answer in c++ primer a while ago, too bad I never realized it was a dupe :( – aaronman Sep 05 '13 at 04:40

1 Answers1

4

An ampresand after the function means that this must be an lvalue, conversely the double ampersand means it must be an rval, the const just says that it's a nonmodifiable lval or rval

So a function qualified with & only works on a modifiable lval and if qualified with && only works on an rval. I guess a const && really makes no sense since a const & can bind to a temporary so the const qualifier only does anything for the lval.

aaronman
  • 17,266
  • 6
  • 57
  • 78