ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

c – 传递rvalue加注不能绑定到左值

2019-08-29 01:07:41  阅读:252  来源: 互联网

标签:perfect-forwarding c c11 templates


该计划如下:

#include <iostream>
using namespace std;

template <typename F, typename T1, typename T2>
void flip2(F f, T1 &&t1, T2 &&t2)
{
      f(t2, t1);
}

void g(int &&i, int &j)
{
      cout << i << " " << j << endl;
}

int main(void)
{
      int i = 1;
      flip2(g, i, 42);
}

编译器抱怨:

error: rvalue reference to type 'int' cannot bind to lvalue of type 'int'

但据我所知,由于T2是用int实例化的,那么t2的类型是int&&,所以应该允许它传递给函数g的第一个参数(int&&).

我的理解有什么问题?

解决方法:

f(t2, t1);

t2有一个名字,所以它是一个左值.它的类型是rvalue,但在表达式中它的类型是左值.为了将它作为右值引用传递,你需要使用std :: forward(这里移动或转换是不合适的,因为T1和T2实际上是通用引用,而不是右值引用,请参阅编辑).

#include <iostream>
using namespace std;

template <typename F, typename T1, typename T2>
void flip2(F f, T1 &&t1, T2 &&t2)
{
      f(std::forward<T2>(t2), std::forward<T1>(t1));
}

void g(int &&i, int &j)
{
      cout << i << " " << j << endl;
}

int main(void)
{
      int i = 1;
        flip2(g, i, 42);
}

http://ideone.com/Aop2aJ

—为什么—

考虑:

template<typename T>
void printAndLog(T&& text) {
    print(text);
    log(text);
}

int main() {
    printAndLog(std::string("hello, world!\n"));
}

当你使用变量的名字时,表达式类型是lvalue(glvalue?); rvalueness被丢弃.否则在上面的例子中,我们丢失了要打印的文本().相反,当我们希望我们的rvalue表现得像一个时,我们必须明确:

template<typename T>
void printAndLog(T&& text) {
    print(text);
    log(std::forward<T>(text));  // if text is an rvalue, give it up.
}

—编辑—

我使用std :: forward因为T1&&和T2&&是通用引用,而不是右值引用. https://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers

标签:perfect-forwarding,c,c11,templates
来源: https://codeday.me/bug/20190828/1756973.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有