c++ - 为什么编译器不选择 `forward`的右值引用版本?

标签 c++ perfect-forwarding

我写了一个类似的std::forward实现,希望找出在这种情况下编译器将选择哪个版本。问题是,似乎从未选择 rvalue-reference 版本。

#include <type_traits>
#include <iostream>
#include <string>
#include <utility>

using std::string;
using std::cout;
using std::endl;
using std::remove_reference;
using std::move;

namespace explicit_return {
template <typename type> type&& forward(typename remove_reference<type>::type&  value) { cout << "cp-"; return static_cast<type&&>(value); }
template <typename type> type&& forward(typename remove_reference<type>::type&& value) { cout << "mv-"; return static_cast<type&&>(value); }
}

void print(string const & value) { cout << "c:" << value << endl; }
void print(string &  value)      { cout << "l:" << value << endl; }
void print(string && value)      { cout << "r:" << value << endl; }

template <typename type> void explicit_print(type && value) {          print(explicit_return::forward<type>(value)); }
template <typename type> void indirect_print(type && value) { explicit_print(explicit_return::forward<type>(value)); }

int main()
{
    string a("perfect");
    indirect_print(a);
    indirect_print(move(a));
    indirect_print("forward");
}


让我们看一下输出
cp-cp-l:perfect
cp-cp-r:perfect
cp-cp-r:forward

最佳答案

您传递给forward<type>的参数是一个变量,因此是l-value

例如,您可能选择了带有额外的std::move或额外的正向的r值重载,例如:

template <typename type> void print_forward2(type&& value)
{
     print(explicit_return::forward<type>(explicit_return::forward<type>(value)));
}

Demo

在实践中,我可以想象将参数存储在tuple中并(一次)重新应用,具体如下:
print(std::forward<Ts>(std::get<Ts>(std::move(my_tuple)))...);

关于c++ - 为什么编译器不选择 `forward`的右值引用版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61202388/

相关文章:

c++ - 具有最少复制的正向仿函数

c++ - 类层次结构中完美转发构造函数和复制构造函数之间的冲突

c++ - 转发参数的可变参数列表

c++ - Scala等与C/C++/Fortran的性能比较?

c++ - 从抽象类中的静态方法调用非静态方法(C++)

c++ - 什么是 `std::reinterpret_pointer_cast`,什么时候应该使用它?

c++ - 使用 std::function 或转发引用作为高阶函数的通用可调用对象输入参数?

C++ 设置 "flags"

c++ - 以实参作为模板形参的模板化函数指针

c++ - std::forward 和带有非常量引用参数的构造函数