mardi 25 mai 2021

Why does decltype(param) say that param is an rvalue reference but I can't call a function accepting rvalue references? [duplicate]

How can I reconcile Scott Meyers' assertion that "all parameters are lvalues" (page 3, effective modern c++) with decltype's response that the parameter is an rvalue reference?

For example, inside the function void bar(std::string&& str) str "has a name" and is an lvalue (I believe). I also cannot call a function expecting an rvalue references inside bar with str as parameter but a function accepting an lvalue reference. However, I was shocked to see that decltype(str) tells me that str is is a rvalue references. How come?

To make things more concrete, consider the following code:

#include <iostream>
#include <string>
using std::cout;
using std::endl;

void foo(std::string&& str) { std::cout << "terminal function" << std::endl; }
void foo2(std::string& str) { std::cout << "terminal function" << std::endl; }

void bar(std::string&& str) {
    cout << std::is_rvalue_reference<decltype(str)>::value << endl;  // true;
    foo(str);                                                        // error
    foo2(str);                                                       // fine
}

Why is std::is_rvalue_reference<decltype(str)>::value true, but I cannot call foo(std::string&&)?

Aucun commentaire:

Enregistrer un commentaire