为什么 decltype(param) 说 param 是一个右值引用,但我不能调用一个接受右值引用的函数?

问题描述

如何将 Scott Meyers 的“所有参数都是左值”的断言(第 3 页,有效的现代 C++)与 decltype 的参数是右值引用的响应相协调?

例如,在函数 void bar(std::string&& str) 中,str“有一个名字”并且是一个左值(我相信)。我也不能调用一个期望在 bar 内使用 str 作为参数的右值引用的函数,而是一个接受左值引用的函数。然而,我震惊地看到 decltype(str) 告诉我 str一个右值引用。怎么来的?

为了使事情更具体,请考虑以下代码

#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
}

为什么 std::is_rvalue_reference<decltype(str)>::value 为 true,但我无法调用 foo(std::string&&)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)