C + + Primer notes--forwarding

Source: Internet
Author: User

Some functions need to forward one or more arguments along with the type to other functions, in which case we need to maintain all the properties of the forwarded argument, including whether the argument type is const and if the argument is an lvalue or an rvalue.

Template <typename F, TypeName T1, TypeName t2>void  func (f F, T1 T1, T2 T2) {    f (T2, T1);} void subfunc (intint &v2) {    + +v2;} int 0  2);    // I did not increase


We can use rvalue references to solve these problems:

Template <typename F, TypeName T1, TypeName t2>void func (f F, T1 &&t1, T2 &&T2) {    F ( T2, T1);} void subfunc (intint &v2) {    + +v2;} int 0  2);    // I added, and can also pass the const


But the function func works well for a function that accepts an lvalue reference, but does not accept the function of an rvalue reference parameter:

Template <typename F, TypeName T1, TypeName t2>void func (f F, T1 &&t1, T2 &&T2) {    F ( T2, T1);} void subfunc (intint &v2) {    + +v2;} int 0  2);    // error, cannot instantiate from an lvalue int&&


To solve these problems, we can use a new standard library called forward to pass the parameters, which preserves the type of the original argument. Forward must be called by displaying template arguments. Forward returns an rvalue reference for the display argument type.

Template <typename F, TypeName T1, TypeName t2>void func (f F, T1 &&t1, T2 &&T2) {    F ( Std::forward<T2> (T2), std::forward<t1> (t1));    // by reference collapse, lvalue or lvalue, right or right value }void subfunc (intint &v2) {    + +v2;} int 0  2);    // correct

C + + Primer notes--forwarding

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.