C++11新特性之 std::forward(完美转发)

上篇博客对右值、右值引用都做了简要介绍。

我们也要时刻清醒,有时候右值会转为左值,左值会转为右值。

(也许“转换”二字用的不是很准确)

如果我们要避免这种转换呢?

我们需要一种方法能按照参数原来的类型转发到另一个函数中,这才完美,我们称之为完美转发。

std::forward就可以保存参数的左值或右值特性。

因为是这样描述的:

When used according to the following recipe in a function template, forwards the argument to another function with the value category it had when passed to the calling function.

例子:

template<class T>
void wrapper(T&& arg)
{
    foo(std::forward<T>(arg)); // Forward a single argument.
}

If a call to wrapper() passes an rvalue std::string, then T is deduced to std::string (not std::string&, const std::string&, or std::string&&), and std::forward ensures that an rvalue reference is passed to foo.

If a call to wrapper() passes a const lvalue std::string, then T is deduced to const std::string&, and std::forward ensures that a const lvalue reference is passed to foo.

If a call to wrapper() passes a non-const lvalue std::string, then T is deduced to std::string&, and std::forward ensures that a non-const lvalue reference is passed to foo.

看一段网站上的代码(http://en.cppreference.com/w/cpp/utility/forward):

#include <iostream>
#include <memory>
#include <utility>
#include <array>

struct A {
    A(int&& n) { std::cout << "rvalue overload, n=" << n << "\n"; }
    A(int& n)  { std::cout << "lvalue overload, n=" << n << "\n"; }
};

class B {
public:
    template<class T1, class T2, class T3>
    B(T1&& t1, T2&& t2, T3&& t3) :
        a1_{std::forward<T1>(t1)},
        a2_{std::forward<T2>(t2)},
        a3_{std::forward<T3>(t3)}
    {
    }

private:
    A a1_, a2_, a3_;
};

template<class T, class U>
std::unique_ptr<T> make_unique1(U&& u)
{
    return std::unique_ptr<T>(new T(std::forward<U>(u)));
}

template<class T, class... U>
std::unique_ptr<T> make_unique(U&&... u)
{
    return std::unique_ptr<T>(new T(std::forward<U>(u)...));
}

int main()
{
    auto p1 = make_unique1<A>(2); // rvalue
    int i = 1;
    auto p2 = make_unique1<A>(i); // lvalue

    std::cout << "B\n";
    auto t = make_unique<B>(2, i, 3);
}
//输出:
rvalue overload, n=2
lvalue overload, n=1
B
rvalue overload, n=2
lvalue overload, n=1
rvalue overload, n=3

最后,记住:

不管是T&&、左值引用、右值引用,std::forward都会按照原来的类型完美转发。

时间: 2024-08-06 12:27:09

C++11新特性之 std::forward(完美转发)的相关文章

C++11新特性之 std::forward(完美转发)(转)

我们也要时刻清醒,有时候右值会转为左值,左值会转为右值. (也许"转换"二字用的不是很准确) 如果我们要避免这种转换呢? 我们需要一种方法能按照参数原来的类型转发到另一个函数中,这才完美,我们称之为完美转发. std::forward就可以保存参数的左值或右值特性. 因为是这样描述的: When used according to the following recipe in a function template, forwards the argument to another

C++11新特性之 std::array container

数组每个人都很熟悉,vector更是我们常常用到的. 但是某些场合,使用vector是多余的,尤其能明确元素个数的情况下,这样我们就付出了效率稍低的代价! 但是你使用数组的代价是那么的不安全,那么的不方便. 于是,C++11推出了模板类array,位于std名称控件中. 与vector不同的是,array对象的长度是固定的,使用了静态存储区,即存储在栈上,效率跟数组相同,但是更加的安全. 首先需要包含头文件array,而且语法与vector也有所不同: #include<array> ...

C++11新特性应用--实现延时求值(std::function和std::bind)

说是延时求值,注意还是想搞一搞std::function和std::bind. 之前博客<C++11新特性之std::function>注意是std::function怎样实现回调函数. 如今就算是补充吧,再把std::bind进行讨论讨论. 何为Callable Objects? 就可以调用对象,比方函数指针.仿函数.类成员函数指针等都可称为可调用对象. 对象包装器 Function wrapper Class that can wrap any kind of callable eleme

C++:C++11新特性超详细版(1)

前言: 虽然目前没有编译器能够完全实现C++11,但这并不意味着我们不需要了解,学习它.深入学习C++11,你会发现这根本就是一门新的语言,它解决了c++98中许多遗留下来的问题.早晚会有一天,C++11便会普及大部分编译器.因此,提早做些准备也是应该的. 在此我想做一个关于C++11的专题,将C++11的新特性进行一一讲解,以通俗易懂的语言及例子帮助读者入门C++11.本文便是C++11新特性超详细版系列文章的第一篇, 即C++:[C++11]新特性超详细版(1). 不过我要强调的是,这些文章

9秒学院学C++11新特性

9秒学院C++11新特性学习笔记 分类: C/C++ 最近学习了C++11的新特性,将学习内容整理下来以巩固记忆,C++11的新特性,可以分为两部分,第一部分是C++11核心语言的特性,第二部分是STL标准库的新特性.学习C++11主要参考了wiki上的一篇文章,在介绍右值引用的时候还参考了MSDN上一篇文章,由于这两篇文章写的时间比较早,和实际有些出入,我的开发环境是win8,vs2012,很多C++11特性还没支持,所以只整理了vs2012已经支持了的特性. 第一部分:核心语言的特性 一.

C++11 新特性之 tuple

我们在C++中都用过pair.pair是一种模板类型,其中包含两个数据值,两个数据的类型可以不同.pair可以使用make_pair构造 pair<int, string> p = make_pair(1, "a1"); 如果传入的参数为多个,那么就需要嵌套pair,如下代码 #include <iostream> #include <map> using namespace std; int main() { //<int, string,

C++11 新特性之 变长参数模板

template <typename ... ARGS> void fun(ARGS ... args) 首先明确几个概念 1,模板参数包(template parameter pack):它指模板参数位置上的变长参数,例如上面例子中的ARGS 2,函数参数包(function parameter pack):它指函数参数位置上的变长参数,例如上面例子中的args 一般情况下 参数包必须在最后面,例如: template <typename T, typename ... Args>

[C++11新特性]第二篇

0.可变数量参数,可变函数模版,变长模版类 c++98可变数量参数 #include<cstdio> #include<cstdarg> double SumOfFloat(int count, ...) { va_list ap; double sum=0; va_start(ap,count); for(int i=0;i<count;i++) sum+=va_arg(ap,double); va_end(ap); return sum; } int main() { p

C++11 新特性(5) 统一初始化

在C++11之前,初始化的类型并非总是统一的. 例如以下两个man定义,一个作为结构,一个作为类.两者的初始化是不一样的. #include <iostream> using namespace std; struct manStruct{ string name; int age; }; class manClass { private: string name; int age; public: manClass(string s,int a):name(s),age(a){ } }; i