【发布时间】:2016-09-02 03:08:50
【问题描述】:
我正在学习std::forward。我编写了一个简短的程序来测试如果我们在将参数转发给另一个函数调用之前不调用 std::forward 会发生什么:
#include <iostream>
#include <typeinfo>
#include <string>
using namespace std;
class Example {
};
ostream &operator << (ostream &os, const Example &e) { os << "yes!"; return os; }
void test_forward_inner(const Example &e) { cout << "& " << e << endl; }
void test_forward_inner(Example &&e) { cout << "&& " << e << endl; }
void test_forward_inner(const string &e) { cout << "& " << e << endl; }
void test_forward_inner(string &&e) { cout << "&& " << e << endl; }
template <typename T>
void test_forward_wrapper(T &&arg) {
test_forward_inner(arg);
}
int main()
{
Example e;
test_forward_wrapper(e);
test_forward_wrapper(Example());
cout << endl;
string s("hello");
test_forward_wrapper(s);
test_forward_wrapper("hello");
return 0;
}
这里我尝试将一个左值和一个右值从test_forward_wrapper() 转发到test_forward_inner()。运行这个程序给出输出:
& example
& example
& hello
&& hello
对于std::strings,调用了所需的内部函数,但对于我自己的类,只调用了左值版本。只有在将参数传递给内部函数之前调用std::forward,才能调用右值版本。
这里有什么不同?据我所知,根据参考折叠规则,当使用Example() 调用包装器时,右值T 将被推断为Example 和arg 将具有类型Example &&,因此右值版本的应该调用内部函数。
而且,对于其他情况,例如这里的std::string 案例,调用了正确版本的内部函数,那么我们可以删除这里的std::forward 吗?如果没有,会发生什么(可能是坏事)?
【问题讨论】:
标签: c++ templates c++11 rvalue-reference perfect-forwarding