在 C++ 中使用 std::forward [英] Use of std::forward in c++

查看:32
本文介绍了在 C++ 中使用 std::forward的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个代码,其中使用了 std::forward.我在谷歌上搜索了很长时间,但无法理解它的真正用途和用途.

I have come across a code, where std::forward is used. I have googled about it for a longtime and not able to understand its real purpose and use.

我在stackoverflow中看到过类似的线程,但还是不清楚.有人可以用一个简单的例子解释一下吗?

I have seen similar threads in stackoverflow, but still not clear. Can somebody explain it with a simple example?

PS:我已经浏览了这个页面,但仍然无法欣赏它的用途.请不要将此问题标记为重复,而是尝试帮助我.

PS: I have gone through this page, but still not able to appreciate its use. Please do not flag this question duplicate and rather try to help me out.

推荐答案

正如您链接的页面所显示的那样:

As the page you linked poses it:

这是一个辅助函数,允许完美转发参数作为对推导类型的右值引用,保留任何潜在的涉及移动语义.

This is a helper function to allow perfect forwarding of arguments taken as rvalue references to deduced types, preserving any potential move semantics involved.

当您有命名值时,如

void f1(int& namedValue){
    ...
}

或在

void f2(int&& namedValue){
    ...
}

评估,无论如何,lvalue.

it evaluates, no matter what, to an lvalue.

再走一步.假设你有一个模板函数

One more step. Suppose you have a template function

template <typename T>
void f(T&& namedValue){
    ...
}

这样的函数既可以用左值调用,也可以用右值调用;但是,无论如何,namedValue 计算结果为 lvalue.

such function can either be called with an lvalue or with an rvalue; however, no matter what, namedValue evaluates to an lvalue.

现在假设你有一个辅助函数的两个重载

Now suppose you have two overloads of an helper function

void helper(int& i){
    ...
}
void helper(int&& i){
    ...
}

f

template <typename T>
void f(T&& namedValue){
    helper(namedValue);
}

总是会调用 helper 的第一个重载,因为 namedValue一个命名值,自然地,评估到 lvalue.

will invariably call the first overload for helper, since namedValue is, well, a named value which, naturally, evaluates to an lvalue.

为了在适当的时候调用第二个版本(即当 f 已经用右值参数调用时),你写

In order to get the second version called when appropriate (i.e. when f has been invoked with a rvalue parameter), you write

template <typename T>
void f(T&& namedValue){
    helper( std::forward<T>(namedValue) );
}

所有这些都在文档中通过以下内容进行了非常简洁的表达

All of this is expressed much concisely in the documentation by the following

需要这个函数的原因是所有命名的值(例如函数参数)总是评估为左值(即使是那些声明为右值引用),这给在转发的模板函数上保留潜在的移动语义其他函数的参数.

The need for this function stems from the fact that all named values (such as function parameters) always evaluate as lvalues (even those declared as rvalue references), and this poses difficulties in preserving potential move semantics on template functions that forward arguments to other functions.

这篇关于在 C++ 中使用 std::forward的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆