lundi 31 mai 2021

Passing an rvalue reference to an overloaded function still results in ambiguity

The code:

#include <iostream>
#include <utility>

void afunc(int)
    {
    std::cout << "\nafunc(int)\n";
    }
    
void afunc(int &&)
    {
    std::cout << "\nafunc(int &&)\n";
    }
    
int main()
  {
  
  int i = 0;
  
  afunc(std::move(i));
  }

The compiler gives me an error saying that the call to afunc is ambiguous.

I am passing an rvalue reference to an int to a function which takes either a value or an rvalue reference for an int. I do not understand why the exact match match is not preferred. It is not as if I am passing something which can be considered an int or an rvalue reference to an int, such as the literal 0, in which case I can understand the ambiguity. The std::move function specifically creates the rvalue reference. Would someone please enlighten me on why the exact match is not preferred and the call is considered ambiguous ?

Aucun commentaire:

Enregistrer un commentaire